如何在shell变量中执行sh命令集?

时间:2015-11-12 09:19:31

标签: linux shell sh

我有这个linux命令:

candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> / dev / null> /tmp/can.log& amp;

直接在shell中运行时,它可以正常工作。

我想用这种方法在我的脚本中添加它:

#!/bin/sh

# I tried this 2 syntax    
# MYVAR="candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> /dev/null > /tmp/can.log &"
MYVAR='candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2> /dev/null > /tmp/can.log &'
$MYVAR

当我执行我的脚本时,我收到此错误:

SIOCGIFINDEX:没有这样的设备

我已经测试过这些脚本并且有效:

#!/bin/sh

MYVAR='ls -l'
$MYVAR

结果:

total 8
drwxr-xr-x  2 root root     0 Nov  5  2015 bin
drwxr-xr-x  2 root root     0 Oct 22  2015 boot
drwxr-xr-x  5 root root 13460 Jan  1 00:00 dev
drwxr-xr-x  8 root root     0 Nov  5  2015 etc
drwxr-xr-x  3 root root     0 Nov  5  2015 home
-rwsr-xr-x  1 root root   258 Nov  5  2015 init
drwxr-xr-x  3 root root     0 Nov  5  2015 lib
drwxr-xr-x  3 root root     0 Nov  5  2015 media
drwxr-xr-x  3 root root     0 Nov  5  2015 mnt
dr-xr-xr-x 67 root root     0 Jan  1 00:00 proc
drwx------  2 root root     0 Oct 22  2015 root
drwxr-xr-x  4 root root     0 Jan  1 00:00 run
drwxr-xr-x  2 root root     0 Nov  5  2015 sbin
dr-xr-xr-x 14 root root     0 Jan  1 00:00 sys
-rwxr-xr-x  1 root root    33 Jan  1 00:04 test
drwxrwxrwt  2 root root     0 Jan  1 00:00 tmp
drwxr-xr-x  9 root root     0 Oct 22  2015 usr
drwxr-xr-x  7 root root     0 Oct 22  2015 var

我看不出错误,你能解释一下这个错误吗?

1 个答案:

答案 0 :(得分:5)

Better (and safer) to use a shell function rather that a variable

#!/bin/sh

myfunc() {
   candump -l -e -x -s 0 -n 10 any,0~0,#FFFFFFFF 2>/dev/null >/tmp/can.log &
}

# call it
myfunc