Don’t execute prepared commands in shellscripts directly
If you prepare a command in a variable and then try to execute that command directly there will be some string-interpolation that can mess up your command.
For example any escaped spaces will become unescaped spaces. To prevent that from happening, always use eval to execute that command.
The following example demonstrates the problem:
with space.txt
The file has been read correctly.
test.sh
sh
#!/bin/sh
# This is the prepared command.
# Notice that it uses a file-name with a space
CMD="cat with\ space.txt"
# Trying to execute the command directly
# Because of string interpolation this is equivalent to:
# cat with space.txt
echo "\n# direct execution"
${CMD}
# Using eval to execute that command
# The string will be taken as it is so this is equal to:
# cat with\ space.txt
echo "\n# using eval"
eval ${CMD}
If you run this script, you will get the following output:
# direct execution
cat: with\: No such file or directory
cat: space.txt: No such file or directory
# using eval
The file has been read correctly.
Post-Meta
- Published: May 28, 2020
- Last modified: May 28, 2020
- Tags: shellscript
Comments