Shell Scripting: Using a variable to define a path

124,721

Solution 1

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

Solution 2

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt
Share:
124,721
Nonameghost
Author by

Nonameghost

Updated on October 03, 2020

Comments

  • Nonameghost
    Nonameghost over 3 years

    My problem lies with my confusion with shell variables.

    To my understanding, variables allow me to store a value (String in this case) and to call it later in my code. So if I wanted to have a variable that holds the path to some set of scripts, I could ideally just store it like this:

    SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
    
    //Later on in the script//
    cd $SPTH
    ./script1
    

    What I'm trying to do, with probably the wrong syntax, is to set the path to variable SPTH.

    Then I use cd with argument $SPTH.

    Ideally this would allow me to run the file there without typing in the path. However it doesn't work. The $SPTH is ignored and the result is as if cd was used alone.

    So what am I doing wrong? And what would be a way to do this?

  • Nonameghost
    Nonameghost over 12 years
    Thank you very much! Now works like a charm, I'll have to remember this.
  • Eatdoku
    Eatdoku over 8 years
    what if there is a space in the path
  • Web User
    Web User over 8 years
    @Eatdoku when using SPTH in your script and its value has a space, then surround the variable with double quotes. E.g. cd "$SPTH"
  • redfox05
    redfox05 about 6 years
    Can this be run without the need for CD? I was thinking command $SPTH but that seems somehow risky. Maybe I need to variable the path, but hardcode the script name? command $SPTH/somescript.sh ?