0

I want to run a script like below:

for i in `cat`;do 
result=command $i |awk '{print $2}'  ## it may give us the exact anwer or error like "command not found"
echo "$i - $result"  
done

for every $i, I want to print:


$i - $result    # if success
$i - NO RESULT  # if I got command not found error

  • This is basic error handling in shells like bash and zsh. You should probably read the documentation on the shell in which you're going to be writing this script. man bash or man zsh should get you started in the right direction. – Thomas N Feb 20 '17 at 19:02
1
while read -r cmd; do
    result=$( command $cmd 2>/dev/null || echo "Just a boring error" )
    printf '%s\t- %s\n' "$cmd" "$result"
done

Read will read from the standard input of the shell, line by line. If you try to use for cmd in $(cat), the cat process will need to exit before any part of the loop is run. With the above loop, each iteration is done as the lines arrive on standard input.

The result variable will get the output of the command substitution. The command substitution will return the output of the command, or the echo if the command in $cmd exited with a non-zero exit status.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.