LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Blogs > linux-related notes
User Name
Password

Notices


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 08:40 PM by the dsc
Updated 01-16-2024 at 08:28 PM by the dsc (adding more trickery)

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

Code:
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
Code:
pf ()
{
for i in "${@:2}" ; do
mv -i "$i" "$1-$i"
done
}
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.

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

The result should be

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



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:

Code:
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 }'`

 USAGE=${USAGE%%.*}
It would suffice to have something like:

Code:
info=(`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1`)
USAGE=${info[0]%%.*}
PID=${info[1]}
PNAME=${info[2]}
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:

Code:
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:
http://stackoverflow.com/questions/1...w-keys-in-bash
Code:
# This will bind the arrow keys

while true
do
    read -r -sn1 t
    case $t in
        A) echo up ;;
        B) echo down ;;
        C) echo right ;;
        D) echo left ;;
    esac
done
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:
Code:
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:
Code:
PS1="\033]0;\w\007${PS1}"
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.
Code:
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...
Code:
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:

Code:
<match target="pattern"><!-- Replace Arial -->
  <test qual="any" name="family"><string>Arial</string></test>
  <edit name="family" mode="assign_replace"><string>Arimo</string></edit>
 </match>
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:
Code:
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:
Code:
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:
Code:
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:
Code:
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).


☻☻☻ "date" command without a leading space in its output
If one's trying to have some cron-like script to do certain things at certain times, with maybe a "case-esac" handling of the output of "$(date +%k)", one can be a bit puzzled on why it fails. While "%k" insteard of "%H" for hours gets rid of the leading zero and thus allows for simple arithmetic operations with bash itself (which can handle "01+01" only "1+1)), in fact "%k" has a space instead of a leading zero.

date +%-k (minus k) gets rid of it and then allows for both bash-arithmetic and case-esac handling


☻☻☻ simple "coin flip" in bash
If for some reason you want to randomly decide whether a script does something or something else, a simple coin flip can be:
Code:
((RANDOM % 2)) && echo head || echo tail
Which obviously can be also conveniently defined as a function.
Posted in Uncategorized
Views 2489 Comments 4
« Prev     Main     Next »
Total Comments 4

Comments

  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.

    http://www.imagebam.com/image/b2ffbf438020349
    Posted 09-27-2015 at 12:09 PM by rokytnji rokytnji is offline
  2. Old Comment
    Jessies package manager version is too old also

    Code:
    harry@biker:~
    $ mpv https://www.youtube.com/watch?v=DI9irFLcVgA
    Playing: https://www.youtube.com/watch?v=DI9irFLcVgA
    [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

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

    Code:
     youtube-dl --version
    2015.01.23.4
    (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 12:47 PM by the dsc the dsc is offline
    Updated 09-30-2015 at 12: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.

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

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

  



All times are GMT -5. The time now is 02:48 AM.

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