Skip to content
Advertisement

How to execute sh command set in shell variable?

I have this linux command:

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

It works correctly when I run it directly in shell.

I want to add it in my script with this method:

#!/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

When I execute my script I get this error:

SIOCGIFINDEX: No such device

I have tested these script and it works:

#!/bin/sh

MYVAR='ls -l'
$MYVAR

Result:

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

I can’t see the error, can you explain me the error?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement