my own bash tricks

read a file well

cat -v ~/.bashrc  

print percentage from youtube-dl

  while read  line ; do  echo $line ; done < <(youtube-dl -t http://www.youtube.com/watch?v=I_GqWPueveE|stdbuf -o0 tr '\r' '\n'   |mawk  -W interactive  '{ print int($2+0) }')

two array print alternatively a and b

  a=(1 2 3) ; b=(a b c ) ;  for ((i = 0; i <=${#a[@]} ; i++ )) ; do printf "%s %s " "${a[i]}" "${b[i]}" ; done

Create menu with kdialog using 2 array
this is not good for kdialog expecially if you have special characters with menus

NOTE

 kdialog --menu "title"  -- MENU-OPTION-1 MENU-TAG-1 MENU-OPTION-2 MENU-TAG-2

means end of options and this is essential to avoid error due for example from

-ab 128k

this code was realaborated here

http://stackoverflow.com/questions/8443515/create-dynamic-options-menu-with-kdialog-bash-script-printf-cant-do-the-job

example file to read $HOME/FFmpeg_profiles.lst

mpeg  -vcodec mpeg2 stuff -ab 1000k
avi  -vcodec avi stuff -ab 1000k
mp3 -acodec mp3 stuff -ab 128k

script i did

function_load_profiles(){
k=0
while read line; do

nameprofile[$k]="$(echo "$line" | awk '{print $1}')"
ffmpegoptionprofile[$k]="$(echo "$line" | awk '{ for(b=2; b<=NF; b++) {printf("%s ", $b)} } ' )"

k=$(( $k+1 ))
done < "$HOME/FFmpeg_profiles.lst"

}

function_load_profiles

ARGS="--menu \"choose your profile\" --"
for ((i=0; i<${#nameprofile[@]}; i++)); do
ARGS="$ARGS \"${ffmpegoptionprofile[$i]}\" \"${nameprofile[$i]}\""
done

SELECTED_OPTIONS=$(echo $ARGS | xargs kdialog)
echo $SELECTED_OPTIONS

replace a word without sed

 a="hi bastards"  ; echo ${a/hi/fuck}

replace every character with

a=*hello*; echo $a ; b=${a//\*/} ; echo $b 

compress folders wihtout .svn stuff

  for folder in */ ; do zip -r ${folder%/}.zip "$folder" -x "*.git*" -x "*.svn*" -x "*~"  ; done

list some files kind with find xD

  ind  /etc/apt/sources.list.d/ -path *.save

list files ignoring a *.svn folder

list files less some kind

  find . -path '*/.svn' -prune -o -type f -print 

Find *.txt file but ignore hidden .txt file

  find . -type f \( -iname "*.txt" ! -iname ".*" \) 

check which folder is the biggest

 du -m --max-depth=1 --exclude=home --exclude=archivio --exclude=proc 2>/dev/null | sort -n 

run desktop console and execute NOT TESTED

xdotool search –name “Desktop Shell Scripting Console – Plasma Desktop Shell” windowactivate key ctrl+e key ctrl+w

simulate typing on the terminal

 echo "You can simulate on-screen typing" | pv -qL 40  

find what is changed last minute

find . -mmin -1 

see picture , video and pdf wihtout X server , YOU MUST BE On video groups , sudo adduser $USER video , and you must be on terminal login , i mean in a session without X server , ctrl alt f1 , to go back crtl alt f7

fbi /home/stuff/picture.jpeg 

 

fbgs /home/stuff/document.pdf 

 

cvlc /home/stuff/movie.avi 

 

bash name renaming folder  extension etc

#get only the name with extension
line=/usr/bin/stuff.ugly ;name="${line##*/}"  ; echo $name

#get the path only
line=/usr/bin/stuff.ugly ;name="${line%/*}"  ; echo $name

#get the path with the name without extension
line=/usr/bin/stuff.ugly ;name=${line%%.*}  ; echo $name

#get only the name without container forlder and without extension
 line=/usr/bin/stuff.ugly ;name="${line##*/}" ; name=${name%%.*}  ; echo $name

#simulate the typing of alt f2

xdotool key alt+F2

#awk without awk

 IFS=- read -r y m d <<< "2003-12-24"; echo "$d.$m.$y"

 

code=() ; format=() ; desc=() ; while IFS="         " read -r c f d; do code+=("$c"); format+=("$f"); desc+=("$d"); done<<<"$(youtube-dl -F http://www.youtube.com/watch?v=dYw4meRWGd4 | grep -A 20 DASH )";  echo ${code[1]} ${code[2]}

# same of before

 IFS=. read -a foo <<< "2012.foo-bar.whatever"; echo ${foo[1]}

#usefull stuff for servers password and login

aserver=(); alogin=();apas=(); i=0; while IFS=/ read -a line ; do aserver[$i]=”${line[0]}”;alogin[$i]=”${line[1]}” ;apass[$i]=”${line[2]}”; i=$(($i+1)) ; done<“$decryptedfile”

add logo centered to a wallpaper

composite  -gravity center kdelogo.png wallpaper.png  output.png

CHECK

#check if doesn't exist a folder

a=&quot;$HOME/bin&quot;
if [[ ! -d &quot;$a&quot;  ]] ; then
mkdir &quot;$a&quot;
else
echo $&quot;folder $a exist&quot;
fi

save nasty code

REMEMBER TO QUOTE THE FILE PATH OR ==> : ambiguous redirect ERROR

 sudo -i ; cat  &lt;&lt;'EOF'&gt;&gt; &quot;/usr/bin/kubuntu-kde-reinstaller&quot;
#!/bin/bash
a=$(apt-cache show kubuntu-desktop | awk '/Depen/ || /Rec/{ gsub(/\,/,&quot;&quot;) ;gsub(/Recommends:/,&quot;&quot;);gsub(/Depends:/,&quot;&quot;); print} ' | awk '{ printf &quot;%s&quot;, $0 }')
sudo apt-get remove $a
sudo apt-get install $a
EOF
sudo chmod +x /usr/bin/kubuntu-kde-reinstaller 

CHECK HOW MANY COMPUTERS ARE ON LINE IN YOUR OWN NETWORK

IFS=. read -a addr &lt;&lt;&lt;&quot;$(ifconfig |awk '/inet addr:192/{gsub(/inet addr:/,&quot;&quot;); print $1}')&quot; ; lanaddress=${addr[0]}.${addr[1]}.${addr[2]}; echo this is your lanaddress $lanaddress ;for ip in $(seq 1 254);do ping -c 1 &quot;$lanaddress.$ip&quot;&gt;/dev/null; if [[ $? -eq 0 ]];then echo &quot;192.168.1.$ip UP&quot;; else echo &quot;$ip DOWN&quot;; fi; done

COPY ONLY FOLDER STRUCTURE

  cd destination/dir;  find /source/dir -type d -printf &quot;%P\n&quot; | xargs mkdir -p 

EXTRACT ONLY LINKS

  lynx --dump https://www.kernel.org/pub/linux/kernel/v3.0/  

RECORD TERMINAL ACTIVITY

  ttyrec myfilename 

PLAY RECORDED TERMINAL ACTIVITY

  ttyplay myfilename  

WAKE UP COMPUTER AT SPECIFIC TIME

 rtcwake -m mem -s 60

 

sudo rtcwake -m mem -l -t $(date +%s -d ‘tomorrow 06:30’)

 

-a | --auto
              Reads the clock mode (whether the hardware clock is set to UTC or local time) from /etc/adjtime. That's the
              location where the hwclock(8) stores that information. This is the default.

       -l | --local
              Assumes that the hardware clock is set to local time, regardless of the contents of /etc/adjtime.

-m mode | --mode mode
              Use standby state mode. Valid values are:

              standby
                     ACPI state S1. This state offers minimal, though real, power savings, while providing  a  very  low-
                     latency transition back to a working system. This is the default mode.

              mem    ACPI  state  S3  (Suspend-to-RAM).  This state offers significant power savings as everything in the
                     system is put into a low-power state, except for memory, which is placed  in  self-refresh  mode  to
                     retain its contents.

              disk   ACPI  state S4 (Suspend-to-disk). This state offers the greatest power savings, and can be used even
                     in the absence of low-level platform support for power management. This state operates similarly  to
                     Suspend-to-RAM, but includes a final step of writing memory contents to disk.

              off    ACPI  state  S5  (Poweroff).  This is done by calling '/sbin/shutdown'.  Not officially supported by
                     ACPI, but usually working.

              no     Don't suspend. The rtcwake command sets RTC wakeup time only.

              on     Don't suspend, but read RTC device until alarm time appears. This mode is useful for debugging.

GREP FROM http://nixtricks.wordpress.com/2009/09/25/grep-and-or-these-but-not-those/

edited byme

#Recursive grep , check every file  in a folder with grep
grep -r hello /home
grep -ri hello /home
#Match pattern1 OR pattern2 in the same line:
grep -E 'pattern1|pattern2' filename

#Match pattern1 AND pattern2 in the same line:
 grep -E 'pattern1.*pattern2' filename

#The above command searches for pattern1 followed by pattern2. If the order does not matter or you want to search them in either order, then use the follwoing

#grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
The pipe enables the OR search which we saw earlier. Another option for this situation (i.e., AND search when the order is not important):

#grep -E 'pattern1' filename | grep -E 'pattern2'
which basically greps the STDOUT of the first grep.

#Match pattern1 AND pattern2, but NOT pattern3 in the same line:
 grep -E 'pattern1.*pattern2' filename | grep -Ev 'pattern3'

#when the order of the first two patterns is important. When that order is NOT important:
grep -E 'pattern1' filename | grep -E 'pattern2' | grep -Ev 'pattern3'

#Match pattern1 OR pattern2, but NOT pattern3 in the same line:
grep -E 'pattern1|pattern2' filename | grep -Ev 'pattern3'

#Match pattern and print the next 15 lines
dmidecode | grep -A 15 Memory

#N.B. (1) grep -E may be replaced by egrep. I used grep -E everywhere in this post assuming a general case of regular expressions as patterns. Lowercase -e is also used for regex, but this is more “basic” than -E which supports “extended” regex, e.g. regular expression metacharacters like +, ?, | and (). (2) The -v flag is for non-matching grep.

FIND THE LATEST FILES MODIFIED ON A FOLDER

 find $1 -type f -exec stat --format '%Y :%y %n' {} \; | sort -nr | cut -d: -f2- | head  

CHECK IF A FOLDER HAS CHANGED , CREATED FILE

sudo apt-get install inotify-tools ; inotifywait -m -e create /tmp  

GET CODECS FROM FFMPEG

VIDEO CODECS

ffmpeg -codecs 2&gt;&amp;1 | grep video | cut -c9-24  

AUDIO CODECS

ffmpeg -codecs 2&gt;&amp;1 | grep audio | cut -c9-24  

TAKE A PICTURE FROM YOUR WEBCAM WITH FFMPEG

ffmpeg -f video4linux2 -i /dev/video0 -vframes 2 test%3d.jpeg 

TAKE A PICTURE FROM YOUR WEBCAM WITH FFMPEG BIGGER RESOLUTION

ffmpeg -f video4linux2 -i /dev/video0 -s 1024x800 -vframes 2 test%3d.jpeg 

TAKE A PICTURE FROM YOUR WEBCAM -b buffer -j 100 quality jpeg

streamer  -c /dev/video0 -b 32 -j 100 -o tes14.jpeg 

GET RAM INFO

sudo lshw -short -C memory 

or

sudo dmidecode | grep -A 15 Memory 

or with dmesg if you have luck

dmesg |grep -i memory |grep core 

PRINT EVERY FUNCTIONS DECLARED INTO YOUR BASHRC

declare -F

PRINT A FUNTION DECLARED ON YOUR BASHRC

declare -f FUNCTIONNAME 

OPEN A PORT WITH MINIUPNP

upnpc -a $(hostname -I) 8112 8112 UDP

SET NETCAT listening on port 8111 tcp

nc -lv 8111

SET NETCAT listening on port 8111 UDP

nc -luv 8111

GET NUMBER OF CORES

grep -c ^processor /proc/cpuinfo

SAVE NASTY CODE

 sudo -i ; cat  &lt;&lt;'EOF'&gt;&gt; /usr/bin/kubuntu-kde-reinstaller
#!/bin/bash
a=$(apt-cache show kubuntu-desktop | awk '/Depen/ || /Rec/{ gsub(/\,/,&quot;&quot;) ;gsub(/Recommends:/,&quot;&quot;);gsub(/Depends:/,&quot;&quot;); print} ' | awk '{ printf &quot;%s&quot;, $0 }')
sudo apt-get remove $a
sudo apt-get install $a
EOF
sudo chmod +x /usr/bin/kubuntu-kde-reinstaller 

SEND FILES FROM LINUX TO LINUX

computer receiver:

nc -4v -l 8000 &gt; file 

computer sender :

cat file.opus | nc -v4 my-ip-address 8001

CHAT USING ONLY THE TERMINAL KNOWING AN IP

COMPUTER 1

upnpc -a $(hostname -I) 8001 8001 TCP ; nc -4v -l 8001  

COMPUTER 2

upnpc -a $(hostname -I) 8001 8001 TCP ; nc -v4 my-ip-address 8001

REMOVE DUPLICATED FROM AN ARRAY

a=(foo bar foo bar &quot;test 1&quot; &quot;test two&quot;) ; declare -A seen=();uniq_arr=() ;for elem in &quot;${a[@]}&quot;;do if ((!seen[&quot;$elem&quot;]++));then uniq_arr+=( &quot;$elem&quot;);fi;done; echo ${uniq_arr[@]}

REMOVE DUPLICATED STRING WITH UNIQ note you need to use sort or uniq will not work

a=(foo bar foo bar &quot;test 1&quot; &quot;test two&quot;)
i=0
while read line ; do
	c[$i]=&quot;$line&quot;
	i=$(($i+1))
done &lt;&lt;&lt;&quot;$(uniq &lt;&lt;&lt;&quot;$(printf -- '%s\n' &quot;${a[@]}&quot;| sort)&quot;)&quot;

COPY BASH ARRAY IN ANOTHER ARRAY

a=(foo bar &quot;foo 1&quot; bar) ; b=(&quot;${a[@]}&quot;); for value in &quot;${b[@]}&quot; ; do echo &quot;$value&quot; ; done

SEND MAILS FROM BASH

echo “This is the body” | mail -s “This is the subject” TO_USER@gmail.com — -f FROM_USER@gmail.com

CHECK IF A PORT IN THE ROUTER IS OPEN OR NOT

ip=$(dig +short myip.opendns.com @resolver1.opendns.com); nmap -p U:20000-20001,T:20000-20001 $ip  

6 Responses to my own bash tricks

  1. Your way:-
    kdialog --menu “title” – MENU-OPTION-1 MENU-TAG-1 MENU-OPTION-2 MENU-TAG-2

    Another way:-
    kdialog --menu 'Pick one action to display, or two to win a prize!' "mpeg -vcodec mpeg2 stuff -ab 1000k" MPEG "avi -vcodec avi stuff -ab 1000k" AVI "mp3 -acodec mp3 stuff -ab 128k" MP4 "*we're* %special& \yeah" 'Special Characters'
    mpeg -vcodec mpeg2 stuff -ab 1000k

    • nowardev says:

      well quoting is very important buts … try to do the same thing from a file, the options that you have put in that menu are read from a file it’s not static

  2. well quoting is very important Basically – yes.🙂

    You’ll find it works fine in files – and with $VARIABLES (which is why it hasn’t been changed in over a decade!). Guess you haven’t had time to actually try it.

    I’d have used yours as a working example but unfortunately your page markup renders it weirdly and I can’t quickly work out what you were trying to do e.g. “&-lt” shows as “&lt”, and “--menu” shows as “-menu”.

  3. The problem you probably encountered is two-fold:-
    ;1. kdialog interprets any menu argument beginning with “-” as the start of an argument. This can be overcome by either putting a space before the “-” (e.g. “ -“) or using the undocumented method you found. The problem doesn’t apply to “special characters” only the minus sign as the first character in a menu Option (dialog and xdialog do the same).

    ;2. kdialog --help doesn’t document using “--” before the menu Options and Arguments to prevent that happening. It’s documented in man dialog (kdialog may one day be compatible with dialog).

    btw i consider this blog my own stuff i mean i write here for 99% for my self use but i have seen that people read it too

    Well you get that when you put it on the internet!😀 (I found it looking for ways to force two columns of Options into a Kdialog menu).

    • nowardev says:

      a little correction kdialog says : — End of options
      try this

      kdialog –help | grep -i “end of options”

      btw I have not even noticed🙂 overflow forum was helpfull😀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: