Download your favorite Linux distribution at LQ ISO.
Go Back > Blogs > linux-related notes
User Name


Just annotations of little "how to's", so I know I can find how to do something I've already done when I need to do it again, in case I don't remember anymore, which is not unlikely. Hopefully they can be useful to others, but I can't guarantee that it will work, or that it won't even make things worse.
Rate this Entry

Collection of random small tricks

Posted 09-26-2015 at 09:40 PM by the dsc
Updated 12-04-2018 at 08:33 PM by the dsc (adding more trickery)

☻☻☻ Pipeing youtube-dl output to a given player (and having it as a mini-script)

youtube-dl -f ${2:-5} $1 -q -o - | mpv -
The first parameter is the youtube url, for a single video, and the second, optional, the quality code, like "best", "worst", or a given number. The default there (5) is the 240p flv.

Just "mpv youtube-URL" was supposed to work, but isn't working right now for me. It says the youtube-dl version is old, but I'm not sure that's the case.


☻☻☻ Tiny script/function to rename files just adding an arbitrary prefix
pf ()
for i in "${@:2}" ; do
mv -i "$i" "$1-$i"
Written here as a function for those who use a single file to store dozens of little semi-aliases tiny scripts instead of having each one in a separate file, but that's obviously an option, too, stripping the function declaration part.

pf prefix file1.txt anotherfile.txt file30.bla fileABC.txt yet-another-file-related-to-the-prefix.txt

The result should be


Note to self and others: do some tests with dummy files for filenames with spaces. Apparently it works just escaping spaces with "/" as "tab" would do automatically, buy maybe quotes are preferable, or yet, maybe you can't use quotes. In which case a future improvement should perhaps grep for such potential issues and exit with error and some explanation about it, or something like that.


☻☻☻ Use a lowercase "version" of an extant bash $string: ${string,,}

☻☻☻ Delete broken symlinks: find -L -maxdepth 1 -type l -exec trash-put {} \;
(See this post for the explanation)

☻☻☻ Escape a bash string (its contents) automatically: printf 'q' "$string"

☻☻☻ Avoid accidental hidden options/parameters with a last-parameter parameter: for many commands, you can use "--" to state that, after that, there are no more "flags", things like "-a" or whatever. E.g.: mv -i -- ./* /somewhere-else. Without the "--" an eventual weird file named "-whatever" would make bash understand things as "mv -i file1 file2 -w hatever /somewhere".

☻☻☻ Avoid unnecessary commands and repetitions. The most basic thing to avoid are things like "cat | grep | sed", when just sed would do it. But not rarely you'll see some conceptually interesting scripts doing some other unnecessary repetitions, like this one, a daemon to manage high cpu usage in bash. Instead of having something like:

USAGE=`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1 | awk '{ print $1 } '`
PID=`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1 | awk '{print $2 }'`
PNAME=`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1 | awk '{print $3 }'`

It would suffice to have something like:

info=(`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1`)
The "ps" command is run only once, and awk is not needed; instead of running the same command three times and parsing the output three times, do it just once into an array, and instead of "parsing", just use the index number, labeling it as a variable itself, for clarity sake.

☻☻☻ "Reverse"/"negative" wildcards in bash - requires "shopt -s extglob" first. If you want only files that don't have "notthis" as part of their file name:

for file in !(*notthis*) ; do echo $file ; done
# it's also taken by some commands such as "ls"
#ls -d !(*notthis*)
To exclude multiple patterns, separate them with this character "|": ls !(*nothis*|*northat*)

☻☻☻ Read arrow keys in bash - from stack overflow:
# This will bind the arrow keys

while true
    read -r -sn1 t
    case $t in
        A) echo up ;;
        B) echo down ;;
        C) echo right ;;
        D) echo left ;;
But worth mentioning that the arrow keys are actually several keys in a row. So A, B, C, and D are just the first of a short string. Therefore, if you have this code, plus "*) echo other thing ;;", any of the arrows will also echo "other thing", even though it would ordinarily be the "case" for "any other" thing, not previously specified. That thread has also other, more sophisticated approaches to this, besides the suggestion of avoiding it altogether for simplicity sake.

☻☻☻ "find-like" ls output, with full path, and recursive. Somewhat faster than "find", depending on what you're planning:
ls -R1 $PWD | while read l ; do case $l in *:) d=${l%:} ;; "") d=;; *) echo "$d/$l" ;; esac ; done
%PWD is the variable for the current folder. Please don't do ls `pwd` and much less ls $(echo "$(pwd)") and such things. You could even "grep" some filename/subfolder for an even more find-like application, if that's for whatever reason handier than "find" itself.

☻☻☻ filter multiple extensions/patterns with ls: ls *.{mp3,avi,mp4,aac,mkv}
Without a preceding "shopt -s nocaseglob" you'd need all possible/likely permutations of lower and uppercases for each pattern.

☻☻☻ Lxterminal window title as the current running job or working folder -- I have the impression some terminal emulators do that automatically, but in case they don't, you can achieve this effect by adding this at the end of your .bashrc:
trap 'echo -ne "\033]0;$BASH_COMMAND\007" > /dev/stderr' DEBUG
Then it's easier to spot which terminal you want to find out from some alt+tab task selector or something.

☻☻☻ reduce dramatically the file size of mp3 with bearable quality for non-musical stuff. Like podcasts, where the most smooth and beautiful sounding voices isn't a requirement, but mostly comprehension.
for i in *.mp3 ; do nn=${i/.mp3/_vbr.mp3} ; lame --mp3input -m m -q 2 -v --vbr-new -V 9 -b8 -B 20 "$i" "$nn" ; done
In my "offline" notes from where I got this, I've noted also that "-m m" may "erase some of the tracks, dumb mono".

Combining with methods to speeding up the tracks* you can achieve further reduction in file size, and not rarely people speak too slowly. The bad side is that once you get used to always hear speed-up stuff in almost everything a person says, then you listen her speaking in normal speed, it sounds like she's kind of drunk/groggy.

* I think pure "sox" or some other program can do it, not needing the wav conversion and all, but only between mp3 or certain other format(s), and not with the same degree of freedom to chose the play rate, for some reason. Here's a "updated" one-liner version that uses just ffmpeg and lame to do the whole thing.

☻☻☻ To kill mate-notification daemon, sometimes, if for some reason you want to (clearing all current notifications at once, and not necessarily preventing new notifications to pop up), and pkill isn't being able to, it seems that this works as an alternative: kill -kill $(pidof mate-notification-daemon)

☻☻☻ Have bold or some other formatting in gxmessage buttons. Convert the desired text to a plain text copy-and-paste-able but formatted version with this site. Then use simply use gxmessage with the pasted text...
gxmessage -buttons "𝗯𝗼𝗹𝗱:2,ⓞⓣⓗⓔⓡ:3,𝕡𝕤𝕖𝕦𝕕𝕠:4,🅵🅾🆁🅼🅰🆃🆃🅸🅽🅶:5,𝘱𝘰𝘴𝘴𝘪𝘣𝘪𝘭𝘪𝘵𝘪𝘦𝘴:6" "message text here, you can also do this kind of 𝗽𝘀𝗲𝘂𝗱𝗼-𝗳𝗼𝗿𝗺𝗮𝘁𝘁𝗶𝗻𝗴 here, but I think it's more useful for the buttons, but, to each their own."
☻☻☻ Avoid ugly aliased Arial on firefox - for whatever reason, apparently Arial was already being replaced or anti-aliased on Google Chrome, and not on Firefox. Regardless, adding this to ~/.config/fontconfig/fonts.conf can help preventing sharp pixels from scratching your eyeballs:

<match target="pattern"><!-- Replace Arial -->
  <test qual="any" name="family"><string>Arial</string></test>
  <edit name="family" mode="assign_replace"><string>Arimo</string></edit>
Or the comparable font of your choice besides "Arimo". That probably should be within <fontconfig> and </fontconfig>, if I know anything at all about XML. I saw it here.

☻☻☻ Plain tab dropdown list in Palemooon, probably some Firefoxes, instead of tab preview "gallery" - I find quite faster to find the tab I'm looking for just reading than looking for their thumbnail previews, specially if they're on the same site. Go to about:config and set browser.allTabs.previews to "false". You may also like to set browser.ctrlTab.previews to "false" as well, that's for the control+tab cycling.

☻☻☻ Proper way to use strings and preserving multiple spaces - if at some point you have something like "file="multiple . . . consecutive . . spaces . . between . . . words.ext" (without the dots) but then you use -- echo/mv/cp/etc $file -- bash will actually stript the extra spaces automatically (as does this forum's rendering, apparently), and if the file/folder exists, it won't be found/touched; if you wanted to create one with multiple spaces, for some reason, it will fail. The proper way is simply to use instead -- echo/mv/cp/etc "${file}" -- with the curly brackets. Source: askubuntu

☻☻☻ Making control left/right jump words on the bash terminal, and up and down (no control) cycle through bash_history - Adding it to .bashrc does it:
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
bind '"\e[1;5D" backward-word'
bind '"\e[1;5C" forward-word'
For some reason I thought I had it working before somehow, but it stopped working not long ago. I guess it was some setting on .Xresources, which I "deleted".

☻☻☻ Use regex instead of -o to find files of multiple extensions - like so:
find -L /some/path/ -regex '.*\.\(mp4\|mkv\|flv\|avi\)'
☻☻☻ Titlebar clock hack specially interesting for Openbox users who don't have/want a taskbar, or don't want it displaying the clock, or don't mind it, but like it to autohide and having a clock always visible nevertheless. So, since there's often plenty of wasted space in the windows' title bars, a hacky way to put a clock there is achieved as such:
while true; do wmctrl -r :ACTIVE: -N "$(awk -F' \\─\\─\\─\\─\\─\\─' '{print $1}' <<< $(xdotool getwindowfocus getwindowname))                                                                                                                                                                                                                                                                                                                             $(date +"%k:%M")"; sleep 5 ; done &
The empty space is my own touch on it, it pushes the clock to the rightmost part of the titlebar, next to where the close/minimize buttons usually are. On Openbox, at least. A "bug" on it is that there will be always a "..." in a large empty space, though. This and the shorter clock format are the only modifications from this line I copied from an answer at askubuntu.

☻☻☻ Bash auto-completion of filenames according to associated/typically wanted application -- add things like this to your bashrc:
complete -f -X '!*.@(mp4|mp3|mkv|avi|flv|wmv|webm)' mpv
Then if you have "competing" file names with different extensions (for example, a subtitle file with the same name of its video), the auto-completion will exclude all those that don't make sense (or, specifically, those that you don't list there).
Posted in Uncategorized
Views 2025 Comments 4
« Prev     Main     Next »
Total Comments 4


  1. Old Comment
    I just had to test this out out of curiosity. Worked for me in AntiX 15.
    I had installed youtube-dl during my install process. Using Debian Jessie.
    Posted 09-27-2015 at 01:09 PM by rokytnji rokytnji is offline
  2. Old Comment
    Jessies package manager version is too old also

    $ mpv
    [ytdl_hook] Your version of youtube-dl is too old! You need at least version '2014.11.26', try running `youtube-dl -U`. 
    Failed to recognize file format.
    Just for grins

    root@biker:/home/harry# youtube-dl -U
    It looks like you installed youtube-dl with a package manager, pip, or a tarball. Please use that to update.
    Not happening on this install. I like your way better.
    Posted 09-27-2015 at 01:23 PM by rokytnji rokytnji is offline
  3. Old Comment
    The irony is that I get:

     youtube-dl --version
    (And right now 2015.09.28)

    So it's actually mpv that misunderstands the newer version as an old one, perhaps due to deprecated syntax or something.

    Hey, but for some reason with the latest update it worked! Go figure...
    Posted 09-30-2015 at 01:47 PM by the dsc the dsc is offline
    Updated 09-30-2015 at 01:50 PM by the dsc
  4. Old Comment
    Just another box not setup as my previous post but showing what Debian Jessie provides. I am current with dist-upgrades on this box today.

    $ apt-cache policy youtube-dl
      Installed: (none)
      Candidate: 2014.08.05-1+deb8u1
      Version table:
         2014.08.05-1+deb8u1 0
            500 jessie/main i386 Packages
    using cclive on this unit

    $ apt-cache policy cclive
      Installed: 0.7.16-2+b1
      Candidate: 0.7.16-2+b1
      Version table:
     *** 0.7.16-2+b1 0
            500 jessie/main i386 Packages
            100 /var/lib/dpkg/status
    Posted 09-30-2015 at 04:11 PM by rokytnji rokytnji is offline


All times are GMT -5. The time now is 03:20 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration