Hi All,
I have one big script to execute multiple commands based on some condition and log the process.
I am not able to use | there, it is giving below error - refer code: it is small example.
Can we avoid this error ?
[alepo@a2e-rep-db tmp]$ cat test55.sh
#!/bin/bash
a="df -kh|head -2"
echo "$a"
$a
[alepo@a2e-rep-db tmp]$
[alepo@a2e-rep-db tmp]$ sh test55.sh
df -kh|head -2
df: invalid option -- '|'
Try 'df --help' for more information.
[alepo@a2e-rep-db tmp]$
This works fine.
[alepo@a2e-rep-db tmp]$ cat test55.sh
#!/bin/bash
a="df -kh"
echo "$a"
$a
[alepo@a2e-rep-db tmp]$
[alepo@a2e-rep-db tmp]$ sh test55.sh
df -kh
Filesystem Size Used Avail Use% Mounted on
devtmpfs 24G 0 24G 0% /dev
tmpfs 24G 0 24G 0% /dev/shm
tmpfs 24G 41M 24G 1% /run
tmpfs 24G 0 24G 0% /sys/fs/cgroup
/dev/vda1 99G 23G 72G 24% /
/dev/vdc1 6.9T 2.2T 4.5T 33% /data
tmpfs 4.7G 0 4.7G 0% /run/user/54321
tmpfs 4.7G 0 4.7G 0% /run/user/0
tmpfs 4.7G 0 4.7G 0% /run/user/1000
[alepo@a2e-rep-db tmp]$
jake19
March 9, 2020, 9:57am
2
Its failing on the pipe character at |. Try to escape it with a backslash like "df -kh\|head -2"
Hi Jake,
It gives another error.
[alepo@a2e-rep-db tmp]$ cat test55.sh
#!/bin/bash
a="df -kh\|head -2"
echo "$a"
$a
[alepo@a2e-rep-db tmp]$
[alepo@a2e-rep-db tmp]$ sh test55.sh
df -kh\|head -2
df: invalid option -- '\'
Try 'df --help' for more information.
[alepo@a2e-rep-db tmp]$
either:
#!/bin/bash
a=$(df -kh|head -2)
echo "$a"
OR
#!/bin/bash
a='df -kh|head -2'
echo "$a"
eval "$a"
1st is preferred.
2 Likes
Thank you Vgersh.
All these are small test.
[alepo@a2e-rep-db tmp]$ cat abc.txt
A1,df -kh|head -2
[alepo@a2e-rep-db tmp]$
[alepo@a2e-rep-db tmp]$ cat test55.sh
#!/bin/bash
IFS=$'\n'
for i in `cat abc.txt`
do
a=`awk -F"," '{print $2}' abc.txt`
eval "$a"
done
[alepo@a2e-rep-db tmp]$
[alepo@a2e-rep-db tmp]$ sh test55.sh
Filesystem Size Used Avail Use% Mounted on
devtmpfs 24G 0 24G 0% /dev
[alepo@a2e-rep-db tmp]$
or better yet /tmp/a.sh
:
#!/bin/bash
while IFS=, read f1 f2 junk
do
eval "$f2"
done < /tmp/a.txt
$ /tmp/a.sh
Filesystem Size Used Avail Use% Mounted on
C:/cygwin64 236G 98G 139G 42% /
OR (without the eval
):
#!/bin/bash
while IFS=, read f1 f2 junk
do
echo "$f2"
done < /tmp/a.txt | bash
1 Like
Hi
Because the shell must first create a channel and then expand the variables.
And if it expands a variable, it skips the channel creation queue and tries to interpret the entire line as one command
1 Like