1

I have the following bash script I'm now trying to convert to run using the system shell instead:

  1 #!/bin/sh
  2 #testtotal
  3 lines="$(crontab -l | awk '{if(NR>2)print}')"
  4 echo "1..$lines"
  5 counter=1
  6 while read p; do
  7         if [[ -x "$p" ]]
  8         then
  9             echo "ok $counter - $p is executable"
 10         else
 11             echo "not ok $counter - $p is not executable or found"
 12         fi
 13         counter=$((counter+1))
 14 done < <(crontab -l | awk '{if(NR>2)print}' | awk '{print $6}')

when I run using "sh" it fails with the error:

      ctest: line 14: syntax error: unexpected redirection 

Can you tell me how to adapt this to run under bin/sh?

  • 3
    What you have is a bash script with a /bin/sh she-bang line, just to clarify. – Jeff Schaller Mar 22 '18 at 19:43
  • @JeffSchaller yes, when I change the script directive to bash it works fine. but I need to get it working using /bin/sh. – dot Mar 22 '18 at 19:45
  • Try << instead of < <. Spaces do matter. – eyoung100 Mar 22 '18 at 19:49
  • @eyoung100 that doesn't work. that gives another error "syntax error: unexpected "(" . – dot Mar 22 '18 at 19:51
  • 1
    @dot, a minor point, you can write crontab -l | awk 'NR > 2 {print $6}' using only one awk – glenn jackman Mar 22 '18 at 19:54
3

On line 7, instead of [[ ... ]] you want [ ... ] or test ... (making sure to always, always, always quote every variable -- which you've already done, but with [ it's not optional and it's worth repeating for everyone else reading).

if [ -x "$p" ]

On line 14, you can use a here-document combined with a command substitution to replace the process substitution:

done <<EOF
$(crontab -l | awk 'NR > 2 { print $6 }')
EOF

This way you avoid running the while read p loop in a subshell due to piping into it, so your variables will survive.

That should do it to make this POSIX compliant.

  • hi. this works. the only thing is that 'lines="$(crontab -l | awk '{if(NR>2)print}')"" is displaying the results of the command. got to suppress. I guess I can try doing a wc -l insteead... – dot Mar 22 '18 at 19:56
  • I can't reproduce that. Maybe your crontab -l writes to standard error. Try adding 2>&1 to the crontab -l to combine standard error with standard output -- or if you don't want that output, add 2>/dev/null. – Martijn Dekker Mar 22 '18 at 20:01
  • yeah. neither of those work. – dot Mar 22 '18 at 20:04
  • Are you sure? This doesn't work? lines="$(crontab -l 2>&1 | awk '{if(NR>2)print}')" If not, I can't help you. Insufficient information. – Martijn Dekker Mar 22 '18 at 20:07
  • i had to just replace the first line with these two lines: lines="$(cat /etc/crontabs/root|wc -l)" and then also tests="$(($lines - 2))" – dot Mar 22 '18 at 20:07

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.