There are many times, where you want to execute the same command every line of a file, it can be simple printing on the screen or some other manipulation. This simple shell script reads a file line by line and executes the command specified by the user on the line.
$ cat execute_command_per_line.sh if [ $# -ne 2 ] then echo "Usage: execute_command_per_line command filename" exit 1 fi command=$1 filename=$2 while read line do $command $line done < $filename
As you can see that it takes two parameters,
- Command to be executed
- Name of the file
Let’s use a simple command like echo, The file contents are as follows
$ cat system_calls.txt aa_change_hat accept accept4 access acct add_key adjtime adjtimex afs_syscall alarm
Let’s run the above script
$ ./execute_command_per_line.sh echo system_calls.txt aa_change_hat accept accept4 access acct add_key adjtime adjtimex afs_syscall