0

I know the above topic has been discussed before

  • source a .sh file and you retain the environmental variables after you are done with the sh file
  • while ./ a .sh file and you lose the environmental variables after you are done

However, I have the following script, makefile.sh

#!/bin/sh
echo $(pwd)

export PATH=$PATH:$PWD

## source the environment
source environment-setup

When I source the above file, it went through successfully even without exporting PATH. However when I use ./ of the above file, it gives me ./makefile.sh: 7: ./makefile.sh: source: not found.

I have placed environment-setup in the same directory as the makefile.sh. Do we need to do something more? Or am I missing out some subtle differences between source and `./

Regards

1 Answer 1

2

As a result of the shebang, #!/bin/sh, you are using sh and not bash.

source is a shell builtin for bash but not sh so for the script that you are sourcing, source doesn't exist in the environment which leads to the error when you execute the script with ./

There are two ways that you can fix it:

  1. Change the shebang to #!/bin/bash assuming that bash is an available shell on your system and found in /bin.

  2. Change the last line to

    . environment-setup
    

. has the same functionality as source in sh and also in bash and some of the other shells. It's best to use the absolute path to the environment-source file in case it isn't in the current working directory in which you are running the script so that it will work no matter what the cwd is at the time.

. /path/to/environment-setup
3
  • Hey it works perfectly Commented Aug 15, 2022 at 3:16
  • the correct second suggestion would be using posix . with an explicitly relative or absolute path. i.e. . ./environment-setup. . environment-setup wouldn't work if the current directory is not included in PATH. Commented Aug 15, 2022 at 3:48
  • More precisely, source is from csh, while . is from the Bourne shell. Some shells like bash and zsh support both though with variation in behaviour. You need . ./environment-setup if you want the environment-setup in the current working directory to be sourced and not the one in $PATH (with the behaviour varying whether the shell is in POSIX / sh mode or not in both bash and zsh). Commented Aug 15, 2022 at 6:47

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.