문제

I am facing a problem with some sample code in an Ubuntu environment with dash shell.

When the following block of code is executed in dash shell on Ubuntu Server OS, then I got the output as given below.

#!/bin/sh
cmd="ls"
arg=" -lt"
exec "$cmd $arg"

Output1 :

./test3.sh: 4: exec: ls  -lt: not found

But if I run the following modified code then I got the correct output as given below.

#!/bin/sh
cmd="ls"
arg=" -lt"
exec $cmd $arg

Output2 :

root@ubuntu:~/test# ./test3.sh total 6164
-rwxr-xr-x 1 root root      45 Dec 10 05:40 test3.sh
-rw-r--r-- 1 root root   35962 Dec 10 03:29 debug.txt
도움이 되었습니까?

해결책

In the first version, the double quotes protect the space in the exec parameter from being interpreted by the shell, so exec sees a single word with a space in it, "ls -lt". There isn't a program of that name, so it fails. In the second version, the shell sees the space.

You don't need the space in the value of arg, because in the second version you have a space between $cmd and $arg anyway, but it doesn't do any harm. You don't actually need any quotes at all in this simple case, but if you are in the habit of including them, you won't forget them when you need them.

다른 팁

Your first exec is trying to find a command "ls -lt" (with the space included as part of the command name. Whereas your second example (without the use of quotes), is running the command as you intended, with 'ls' being the command and '-lt' being an argument to that command.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top