Linux Shell
From Torben's Wiki
Contents |
Bash commands
rm -rf dir # do not show warning if not existing mkdir -p dir # do not print warning if already existing AND make needed parents
Output
Send program output into file
sh script.sh > log.txt # std output, (errors to terminal) sh script.sh 1> log.txt 2> log-errors.txt sh script.sh 1> log.txt 2>&1 # both into same file
Piping
sh script.sh | less
Filtering of output
sh script.sh | grep tmenke
Loops
Good overview of parameters for if [1]
If
if [ -d "backup.0" ]; then echo "gibts" else echo "gibts nicht" fi
one-liner:
if [ -d "backup.0" ] ; then sudo mv backup.0 backup.1 ; fi
While
Normal loop
i=1 while [ $i -le 4 ] do (( i++ )) done
Endless loop
while : do ... done
For loop
for i in *.txt; do mv "$i" `echo $i | tr ' ' '_'` done
Combine find and some other command e.g chmod
find -type d -exec chmod g+xs {} \;
sed
If you want to replace the text 'asdf' by 'qwert' in all '*.txt' files in a directory at once, use the following command:
sed -i -e 's/asdf/qwert/g' *.txt
get filename without extension
for file in *
do
if [ -f $file ] ; then
name=${file%\.*} # name without extension
echo ${name}
fi ;
done
name=`basename /path/filename.ext .ext` # -> filename for i in *.jpeg; do mv "$i" "`basename "$i" .jpeg`.jpg"; done
current_directory=$( pwd )
Get Date as String
DATE=`date +"%y-%m-%d_%H-%M"` echo $DATE
Tar
get rid of message "removing leading /": use option P
Pause
read -p "Press any key to start backup..."