Bash: Difference between revisions

From DWIKI
mNo edit summary
mNo edit summary
Line 1: Line 1:


*[http://www.gnu.org/software/bash/bash.html Homepage]
*[http://www.gnu.org/software/bash/bash.html Homepage]  


*[http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html]  
*[http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html]  
Line 15: Line 15:
 
 


 


= Tips and tricks =
= Tips and tricks =
Line 92: Line 93:


== add extensions to filenames ==
== add extensions to filenames ==
find . -type f |while read i;do if [[ ! $i =~ .*.txt ]];then mv -v $i $i.txt;fi;done


find . -type f |while read i;do if [[!_$i_=~_.*.txt|! $i =~ .*.txt]];then mv -v $i $i.txt;fi;done
 


== functions ==
== functions ==
Line 122: Line 125:
== Check if disk is mounted ==
== Check if disk is mounted ==


  mountpoint /mnt/foo
  mountpoint /mnt/foo    
 
= FAQ =
 
== unary operator expected ==
 
try qouting your vars
   [[Category:Scripting]] [[Category:Programming]]
   [[Category:Scripting]] [[Category:Programming]]

Revision as of 12:43, 14 January 2022

 

 

Tips and tricks

String manipulation

Remove character from string

VERSION='2.3.3'
echo "${VERSION//.}"

check if var contains substring

$foo =~ .*sub.*

get first character of a string

FIRST=${STRING:0:1}

read without while loop

The problem is scope, try

echo foo bar | { read a b;echo $b; }

check if variable is integer

if [[$foo =~ ^[0-9]+$]]

 

 

move cursor

^b move back 1 char
^f move forward 1 char
alt-b move back 1 word
alf-f move forward 1 word

loops

loop through range of numbers

for i in {0..10};do echo $i;done

 

exit while loop

break

 

skip one in loop

continue

bash history timestamp

HISTTIMEFORMAT="%d/%m/%y %T "

screen and bash history

To make sure all screens write to same history (at least on CentOS and RHEL):

echo "history -a;history -r" > /etc/sysconfig/bash-prompt-screen
chmod +x /etc/sysconfig/bash-prompt-screen

In general:

export PROMPT_COMMAND='history -n'

or

export PROMPT_COMMAND="history -a; history -c; history -r; ${PROMPT_COMMAND}"

add extensions to filenames

find . -type f |while read i;do if ! $i =~ .*.txt;then mv -v $i $i.txt;fi;done

 

functions

function foo() {
   echo $1 $2
 }

convert units

function convertunits() {

       C="$1"
       U="$2"
       debug "converting $C $U"
       case $U in
               "KiB") O=$((C*1000)) ;;
               "MiB") O=$((C*1000*1000)) ;;
               "GiB") O=$((C*1000*1000*1000)) ;;
               "TiB") O=$((C*1000*1000*1000*1000)) ;;
               *) O="convert error in $U" ;;
       esac
       if [ -z "$O" ];then O="convert_error for unit $U";fi
       echo "$O"

}

Check if disk is mounted

mountpoint /mnt/foo      

FAQ

unary operator expected

try qouting your vars