First of all, never run things with sudo
unless it is actually necessary to run them with sudo
. I really cannot emphasize that enough. Unless you get a "permission denied" error, you don't need sudo
and you should not use sudo
. So you don't need sudo ./bar.sh
, just run ./bar.sh
.
Next, you don't need to echo
to get the results of a command. This isn't needed:
echo '$(ps -ef | grep "smbd" | awk '{print $2}')'
All you need is to run the command itself. You don't need the command substitution ($(command)
) or the echo. Just have this in your script:
ps -ef | grep "smbd" | awk '{print $2}'
Note that if you want to get the PID of a running process, you don't really want ps
either. You can just use pgrep smbd
which avoids the problem of the grep
process itself appearing in the results.
Finally, if you want to print a multi-line string as output, you can use a here doc instead of many echo statements. So, putting all that together, you should make bar.sh
like this:
#!/bin/sh
cat <<'EoF'
for pid in $(ps -ef | grep "smbd" | awk '{print $2}'); do
kill -9 "$pid" &> /dev/null
done
EoF
And then run it as ./bar.sh > foo
(no sudo
!).
Or, here's a simpler version of the same approach:
#!/bin/sh
cat <<'EoF'
ps -ef | awk '/smbd/{print $2}' | while read pid; do
kill -9 "$pid" &> /dev/null
done
EoF
Or, even simpler:
#!/bin/sh
printf '%s\n' 'kill -9 $(pgrep smbd)'
Which brings us to the final point of are you sure you really want a script for this? To kill all running smbd
processes, all you need is a single command:
pkill -9 smbd
echo ' '
– acgbox Dec 30 '21 at 13:53foo
to contain? – terdon Dec 30 '21 at 13:59bar.sh
) if it only outputs a fixed string? You could just put that string in a file and runcat bar.txt > foo
instead. Or just edit it intofoo
directly. – ilkkachu Dec 30 '21 at 14:08