Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing commands containing space in Bash

Tags:

bash

shell

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?

like image 291
Epitaph Avatar asked May 07 '09 18:05

Epitaph


People also ask

How do you handle spaces in bash?

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.

How do you represent a space in bash?

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.

How do you escape a space in bash?

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.

Does spaces matter in bash?

You must separate all arguments of a command with spaces. You must separate a command and the argument, that follows after, with a space.


2 Answers

Try changing the one line to eval $cmds rather than just $cmds

like image 67
Bryan Oakley Avatar answered Oct 09 '22 10:10

Bryan Oakley


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
like image 20
andrewdotn Avatar answered Oct 09 '22 09:10

andrewdotn