-1

I need to store the current directory into a variable, so i did:

$current_path='pwd'

Till this point it is correct, but if I use the below one:

MY_FOLDER=$current_path/subFolder1/subFolder2/MyFolder/

and do $MY_FOLDER I am getting an error:

pwd/subFolder1/subFolder2/MyFolder/ : No such file or directory

Can you please tell me how do i use this in shell scripting? (This might be basics but this is my first scripting)

tripleee
  • 175,061
  • 34
  • 275
  • 318
Girija Vk
  • 1
  • 3
  • 2
    Possible duplicate of [Getting current path in variable and using it](https://stackoverflow.com/q/1636363/608639), [Save current directory in variable using Bash?](https://stackoverflow.com/q/13275013/608639), [How to get a variable to have the current dir path?](https://stackoverflow.com/q/35189157/608639), etc. And maybe [How to set current working directory to the directory of the script?](https://stackoverflow.com/q/3349105/608639) – jww Dec 22 '19 at 13:26

1 Answers1

1

When you write $variable at the prompt, the shell will interpolate its value and parse it. The error message you get says that the value is not a valid command name.

Also, the dollar sign in your first assignment is incorrect (I guess you transcribed that incorrectly) and the value you assign is the literal string pwd which is probably not the name of a directory in the current directory; I'm guessing you intended to run the command pwd and store its output.

However, Bash already stores the current working directory in a variable named PWD; so there should be no need to separately call the external utility pwd.

(Maybe you wanted to write `pwd` with backticks instead of regular single quotes 'pwd'? That would be valid syntax, though it's obsolescent and, as you discovered, hard to read. The modern equivalent syntax is $(pwd).)

You should also avoid upper case for your variable names; uppercase is reserved for system variables. (This is a common mistake even in some respected shell scripting tutorials.)

I guess you actually want

current_path=$(pwd)  # needless here, but shows the correct syntax
my_folder=$PWD/subFolder1/subFolder2/MyFolder/

Attempting to run the directory as a command is still an error. If this directory contains an executable named foo with correct permissions, then

"$my_folder/"foo

will execute that script. It's not clear what you expected your command to do; perhaps you are looking fo

cd "$my_folder"

instead? (Notice also the quotes which are optional in this particular case if the output from pwd does not contain any shell metacharacters; but you want your scripts to also work correctly when that is not true.)

tripleee
  • 175,061
  • 34
  • 275
  • 318