Variable Syntax Error with Bash Script (Homework)

后端 未结 5 543
轻奢々
轻奢々 2020-12-11 11:07

I\'m currently working on homework for a Unix course and I\'ve got everything else done but I just can\'t figure out what I\'ve done wrong here. I\'ve done this exact same s

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 11:41

    Update: As the OP discovered, another issue was a malformed shebang line: #/!bin/bash instead of #!/bin/bash (consider using #!/usr/bin/env bash, though).

    A tip beforehand: http://shellcheck.net is a very handy tool for checking shell code for errors.


    @Ube and @kojiro's answers both contain important pointers:

    • ' is used for quoting, so it must either be used inside double quotes, or it must be escaped as \'.

    • No spaces are allowed around the = in variable assignments in bash.

    But there's more:

    • Use $1 to refer to the first argument; $(1) does something fundamentally different: it uses command substitution ($(...)) to execute the enclosed command and return its stdout output; thus, $(1) tries to execute a - most likely non-existent - command 1 and return its output.

    • Always use [[ ... ]] rather than [ ...] in bash; it's more robust and provides more features; case in point: [ $input != 5 ] will break if $input is undefined or empty - you'd have to double-quote it to prevent that; by contrast, it's fine to use [[ $input != 5 ]].

    • All case branches must be terminated with ;; (even the branches that just contain exit commands;).Fine print: the very last branch also works without ;;

    • The if [ -d $finput ] ; then ... statement is missing its closing fi.

提交回复
热议问题