Girija Vk
Girija Vk

Reputation: 1

Store current directory in variable and use a variable to store the path developed from the previous variable

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)

Upvotes: -1

Views: 4040

Answers (1)

tripleee
tripleee

Reputation: 189799

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.)

Upvotes: 2

Related Questions