vinay hunachyal
vinay hunachyal

Reputation: 3891

Understanding script language

I'm a newbie to scripting languages trying to learn bash programming.

I have very basic question. Suppose I want to create three folders like $HOME/folder/ with two child folders folder1 and folder2.

  1. If I execute command in shell like

    mkdir -p $HOME/folder/{folder1,folder2}
    

    folder will be created along with child folder.

  2. If the same thing is executed through script I'm not able get expected result. If sample.sh contains

    #!/bin/sh
    
    mkdir -p $HOME/folder/{folder1,folder2}
    

    and I execute sh ./sample.sh, the first folder will be created then in that a single {folder1,folder2} directory is created. The separate child folders are not created.

My query is

  1. How the script file works when we compared to as terminal command? i.e., why is it not the same?

  2. How to make it work?

Upvotes: 0

Views: 93

Answers (3)

chepner
chepner

Reputation: 531165

bash behaves differently when invoked as sh, to more closely mimic the POSIX standard. One of the things that changes is that brace expansion (which is absent from POSIX) is no longer recognized. You have several options:

  1. Run your script using bash ./sample.sh. This ignores the hashbang and explicitly uses bash to run the script.

  2. Change the hashbang to read #!/bin/bash, which allows you to run the script by itself (assuming you set its execute bit with chmod +x sample.sh).

    Note that running it as sh ./sample.sh would still fail, since the hashbang is only used when running the file itself as the executable.

  3. Don't use brace expansion in your script. You could still use as a longer method for avoiding duplicate code:

    for d in folder1 folder2; do
        mkdir -p "$HOME/folder/$d"
    done
    

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249153

This is probably happening because while your tags indicate you think you are using Bash, you may not be. This is because of the very first line:

#/bin/sh

That says "use the system default shell." That may not be bash. Try this instead:

#!/usr/bin/env bash

Oh, and note that you were missing the ! after #. I'm not sure if that's just a copy-paste error here, but you need the !.

Upvotes: 1

devnull
devnull

Reputation: 123508

Brace expansion doesn't happen in sh.

In sh:

$ echo {1,2}

produces

{1,2}

In bash:

$ echo {1,2}

produces

1 2

Execute your script using bash instead of using sh and you should see expected results.

Upvotes: 1

Related Questions