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?

4
  • 1
    Possible duplicate of How to know if extglob is enabled in the current bash session? Commented Jan 28, 2018 at 6: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 Commented Jan 28, 2018 at 6:47
  • That was it. Can you explain what the preceding dot did? Edit Ok, i got it , it was for sourcing.. Commented Jan 28, 2018 at 7:55
  • source and . are commands for running a script in the current shell. See unix.stackexchange.com/q/182282/70524 Commented Jan 28, 2018 at 7:56

1 Answer 1

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.