I have a file named cmd
that contains a list of Unix commands as follows:
hostname
pwd
ls /tmp
cat /etc/hostname
ls -la
ps -ef | grep java
cat cmd
I have another script that executes the commands in cmd as:
IFS=$'\n'
clear
for cmds in `cat cmd`
do
if [ $cmds ] ; then
$cmds;
echo "****************************";
fi
done
The problem is that commands in cmd without spaces run fine, but those with spaces are not correctly interpreted by the script. Following is the output:
patrick-laptop
****************************
/home/patrick/bashFiles
****************************
./prog.sh: line 6: ls /tmp: No such file or directory
****************************
./prog.sh: line 6: cat /etc/hostname: No such file or directory
****************************
./prog.sh: line 6: ls -la: command not found
****************************
./prog.sh: line 6: ps -ef | grep java: command not found
****************************
./prog.sh: line 6: cat cmd: command not found
****************************
What am I missing here?
Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.
To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.
The shell will interpret that backslash as an escape of the space. The result will be that the command will not break the argument. The other way to escape space in a path is to enclose the path in quotes, which indicates to the executable that everything between the quotes is one argument.
You must separate all arguments of a command with spaces. You must separate a command and the argument, that follows after, with a space.
Try changing the one line to eval $cmds
rather than just $cmds
You can replace your script with the command
sh cmd
The shell’s job is to read commands and run them! If you want output/progress indicators, run the shell in verbose mode
sh -v cmd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With