Search code examples
linuxbashgrep

check if a file starts with a shebang


I try to grep files for the shebang (ex: #!/bin/bash)

the code looks like that

#!/bin/bash

pr_id=$1
files=$(curl https://api.github.com/repos/os-autoinst/scripts/pulls/${pr_id}/files | jq -c '.[].filename')
#checker() {
for n in "$files"; do
    echo "$n"
    if [[ -f "$n" ]] && [[ $(head -1 $n | grep "^#!" > /dev/null) -eq 0 ]]; then
       echo "gonna test $n"
       if [[ $(sed -n '/\t/p' '$n' | wc -l) > 0 ]]; then
          echo "$n is using TAB"
          return 1
       fi
    return 0
fi
done
#}

#checker

however $(head -1 $n | grep "^#!" > /dev/null) -eq 0 doesnt seem to work properly. Actually i have strange behavior and i would like to understand why behaves like that, as this and many answers I have found on SO and they supposed work for others fail for me.

Other things i tried (all return 1 instead of 0

  • head -1 file | grep -F '^#!'
  • head -1 file | grep -E '/^#!/'

Solution

  • $(...) captures standard output, but you are explicitly discarding all output with ... > /dev/null. All you really need is the exit status of grep, which doesn't require the use of [[ ... ]] at all.

    if [[ -f "$n" ]] && head -1 "$n" | grep -q "^#!"; then
          ...
    fi