0

I was trying to test for noclobber option using: if [ -o noclobber ] but it turned nothing.

I set the noclobber option on using: set +o noclobber.

prompt> cat checkoption.sh
#!/bin/bash
if [ -o noclobber ]
     then
          echo "Option is on."
fi
prompt>
prompt> set +o noclobber
prompt> set -o | grep noglobber
noclobber       on
prompt> ./checkoption.sh
prompt>

Any idea why I am not getting a message here?

Vlastimil Burián
  • 27,586
  • 56
  • 179
  • 309
pigeon
  • 107
  • 1
  • 7
  • 1
    Possible duplicate of [How to know if extglob is enabled in the current bash session?](https://unix.stackexchange.com/questions/255338/how-to-know-if-extglob-is-enabled-in-the-current-bash-session) – muru Jan 28 '18 at 06:45
  • 3
    Oh wait, you're running a script. The `noclobber` option is not inherited by the script's shell. Try sourcing it: `. ./checkoption.sh` – muru Jan 28 '18 at 06:47
  • That was it. Can you explain what the preceding dot did? [Edit] Ok, i got it , it was for sourcing.. – pigeon Jan 28 '18 at 07:55
  • `source` and `.` are commands for running a script in the current shell. See https://unix.stackexchange.com/q/182282/70524 – muru Jan 28 '18 at 07:56

1 Answers1

2

Shell options are not inherited between shell sessions, and you are dealing with two shell sessions here:

  1. The interactive session where you set your shell option, and
  2. The shell script's session in which you test for the option.

The shell script will never detect that the option was set in the calling interactive shell session.

Solutions:

  1. Turn your code into a shell function (in e.g. $HOME/.bashrc):

    checknoclobber () { [ -o noclobber ] && echo 'Noclobber is on'; }
    

    Or, for the generic case,

    checkoption () {
        if [ -o "$1" ]; then
            printf '%s is set\n' "$1" >&2
            return 0
        else
            printf '%s is not set (or invalid option name)\n' "$1" >&2
            return 1
        fi
    }
    
  2. Set the option in the script.

  3. Source the script file in the interactive shell with source or with the . command.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936