Bash

I wrote this as a record for future reference of bash commands.

Some useful conditional programming tips for bash script.

1) for

* The for loop is a bit different from other programming languages, as it is used to iterate over a series of "words" within a string.

E.g., the script below will print each folder or filename in the current folder.

#!/bin/bash for i in $(ls); do echo item: $i done

* It can also be used for C-like loop

E.g., the script below will print the number 1 to 10 in sequence.

#!/bin/bash for i in `seq 1 10`; do echo $i done

Real application examples:

pwdDir=$PWD

for i in `ls -d *`; #list all the folders in the current directory

do

echo $i

cd $i

# process something

cd $pwdDir

done

2) While

* Execute some codes while the condition is true.

E.g.,

#!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ]; do echo The counter is $COUNTER let COUNTER=COUNTER+1 done

3) Until

* Execute some codes until the condition is met.

E.g.,

#!/bin/bash COUNTER=20 until [ $COUNTER -lt 10 ]; do echo COUNTER $COUNTER let COUNTER-=1 done

4) find and grep

Examples:

a) find the file named result.txt

find . -name result.txt

b) find the file named result.txt and suppress the "permission denied" warning

find . -name result.txt 2> >(grep -v 'Permission denied' >&2)

c) find and execute command

find . -type f -name *T1w* 2 -exec cp {} /folder2copy/ \; # copy T1w files to a folder

d) list all packages with the name "python"

dpkg -l | grep -i python

5) grep

ifconfig | grep –A 4 eth0 #output 4 lines After "eth0"

ifconfig | grep -B 2 UP #output 2 lines Before "UP"

ifconfig | grep –c inet6 #count number of matches "inet6"

grep –r “function” * # Search a string Recursively in all Directories

References:

1) http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

2) https://www.tecmint.com/12-practical-examples-of-linux-grep-command/

3) https://stackoverflow.com/questions/762348/how-can-i-exclude-all-permission-denied-messages-from-find