Tuesday, July 26, 2016

[Quick Tips: Bash Script]: A Tutorial on Bash Script

A Tutorial on Bash Script

Use bash For Loop In One Line

Run Command 5 Times

for i in {1..5}; do COMMAND-HERE; done
OR
 for((i=1;i<=10;i+=2)); do echo "Welcome $i times"; done

Work On Files

for i in *; do echo $i; done
OR
for i in /etc/*.conf; do cp $i /backup; done

For Loop To Remove Files

Use a Bash For Loop To Delete Files in Unix

for f in /path/to/dir/*.txt
do
   # if file, delete it
   [ -f "$f" ] && rm "$f"
done
See Bash for loop tutorial for more information.

Use a KSH For Loop To Delete Files in Unix

for f in /path/to/dir/*.c~; do
        # if it is a file, delete it
 if [  -f $f ]
 then
   rm "$f"
 fi
done

For While Loop Through File Contents Script

while COMMANDS do COMMANDS done OR
while read line do echo "$line" done < /path/to/input.txt
In this example, read /etc/passwd file line by line using while loop:
#!/bin/bash
while IFS= read -r line
do
  echo "$line"
done < "/etc/passwd"
Another example:
#!/bin/bash
## script.sh ##
_file="${1:-/dev/null}"   #fail safe 
while IFS= read -r line
do
  # Do something on $line
  echo "$line"
done < "$_file"
Run it as follows: chmod +x script.sh ./script.sh /path/to/text/file.name

No comments: