How to properly test a command as a variable that contains spaces?











up vote
1
down vote

favorite












I am trying to create a test whereas the logic is



If mkdir command is successfully executed perform the next actions



What I have are:



FILEPATH=/home/Documents/projectDirectory
CREATE_DIRECTORY=mkdir $FILEPATH


and the test command:



if [ -e $FILEPATH ]; then
echo "${FILEPATH} exists.."
else
#Create the folder: Test it if is created , else exit gracefully.
if [ -e "${CREATE_COMMAND}" ]; then
echo "File created ${FILEPATH}"
else
echo "Error creating the filePath..exiting.."
error_exit "Error creating the filePath..exiting.."
fi
fi









share|improve this question




















  • 1




    Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
    – Gordon Davisson
    Feb 28 at 6:34

















up vote
1
down vote

favorite












I am trying to create a test whereas the logic is



If mkdir command is successfully executed perform the next actions



What I have are:



FILEPATH=/home/Documents/projectDirectory
CREATE_DIRECTORY=mkdir $FILEPATH


and the test command:



if [ -e $FILEPATH ]; then
echo "${FILEPATH} exists.."
else
#Create the folder: Test it if is created , else exit gracefully.
if [ -e "${CREATE_COMMAND}" ]; then
echo "File created ${FILEPATH}"
else
echo "Error creating the filePath..exiting.."
error_exit "Error creating the filePath..exiting.."
fi
fi









share|improve this question




















  • 1




    Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
    – Gordon Davisson
    Feb 28 at 6:34















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I am trying to create a test whereas the logic is



If mkdir command is successfully executed perform the next actions



What I have are:



FILEPATH=/home/Documents/projectDirectory
CREATE_DIRECTORY=mkdir $FILEPATH


and the test command:



if [ -e $FILEPATH ]; then
echo "${FILEPATH} exists.."
else
#Create the folder: Test it if is created , else exit gracefully.
if [ -e "${CREATE_COMMAND}" ]; then
echo "File created ${FILEPATH}"
else
echo "Error creating the filePath..exiting.."
error_exit "Error creating the filePath..exiting.."
fi
fi









share|improve this question















I am trying to create a test whereas the logic is



If mkdir command is successfully executed perform the next actions



What I have are:



FILEPATH=/home/Documents/projectDirectory
CREATE_DIRECTORY=mkdir $FILEPATH


and the test command:



if [ -e $FILEPATH ]; then
echo "${FILEPATH} exists.."
else
#Create the folder: Test it if is created , else exit gracefully.
if [ -e "${CREATE_COMMAND}" ]; then
echo "File created ${FILEPATH}"
else
echo "Error creating the filePath..exiting.."
error_exit "Error creating the filePath..exiting.."
fi
fi






shell-script shell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 at 14:39









Rui F Ribeiro

38.3k1475126




38.3k1475126










asked Feb 28 at 4:08









Jepoy

63




63








  • 1




    Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
    – Gordon Davisson
    Feb 28 at 6:34
















  • 1




    Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
    – Gordon Davisson
    Feb 28 at 6:34










1




1




Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
– Gordon Davisson
Feb 28 at 6:34






Storing commands in variables is generally a bad idea. See BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
– Gordon Davisson
Feb 28 at 6:34












3 Answers
3






active

oldest

votes

















up vote
0
down vote













I'm unsure why you would want to this, but here is a working solution:



FILEPATH=/home/Documents/projectDirectory
CREATE_DIRECTORY="mkdir $FILEPATH 2>/dev/null"
eval $CREATE_DIRECTORY
if [[ $? -eq 0 ]]; then
echo "Directory created"
else
echo "Directory already exists"
fi


This will try to create the folder and pipe any error message to /dev/null (not displaying it). Then it checks the status of the previous command in the if statement and if that was successful (0) then tell you.






share|improve this answer

















  • 1




    I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
    – Gordon Davisson
    Feb 28 at 6:40












  • I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
    – Mikael Kjær
    Feb 28 at 7:20


















up vote
0
down vote













Your current code has the following flaws:





  • CREATE_DIRECTORY=mkdir $FILEPATH:


    1. Since there are no quotes around mkdir $FILEPATH, CREATE_DIRECTORY only holds mkdir as its value.


    2. $FILEPATH is subject of word splitting.

    3. The CREATE_DIRECTORY variable may be exported to the environment of the resulting expansion of $FILEPATH if the first token of such expansion is an external command.




  • [ -e "${CREATE_COMMAND}" ]:


    1. The CREATE_COMMAND variable holds no value, as far as we know. I assume you meant to write CREATE_DIRECTORY.

    2. It doesn't test if mkdir was successful or not.




Also, the if compound command could be used to test if a command succeeded or not:



if command; then
# Code to execute if command succeeded
else
# Code to execute if command failed
fi


So your code could be rewrite as:



FILEPATH=/home/Documents/projectDirectory

if [ -e "${FILEPATH}" ]; then
echo "${FILEPATH} exists..."
else
if mkdir "${FILEPATH}"; then
echo "File created ${FILEPATH}"
else
echo "Error creating the filePath..exiting.."
error_exit "Error creating the filePath..exiting.."
fi
fi


Note that:




  1. The CREATE_DIRECTORY variable is not needed.


  2. [ -e "${CREATE_COMMAND}" ] was replaced with mkdir "${FILEPATH}".






share|improve this answer




























    up vote
    0
    down vote













    I don't really see why you can't just do



    dir='/home/Documents/projectDirectory'

    if ! mkdir "$dir"; then
    printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
    exit 1
    fi

    printf '"%s" created, now doing other things...n' "$dir"


    The call to mkdir will fail if $dir already exists.



    If you need to allow for the directory to exist and only bail out if mkdir fails to create it, then add -p to the mkdir call above, or do an explicit test for the existence of the directory:



    dir='/home/Documents/projectDirectory'

    if [ ! -d "$dir" ]; then
    if ! mkdir "$dir"; then
    printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
    exit 1
    fi

    printf '"%s" createdn' "$dir"
    fi

    echo 'now doing other things...'


    I'm using the -d test here to test whether $dir may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.





    Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.



    Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.



    Related:




    • Why does my shell script choke on whitespace or other special characters?

    • How can we run a command stored in a variable?




    Other things:



    CREATE_DIRECTORY=mkdir $FILEPATH


    This will run $FILEPATH as a command with CREATE_DIRECTORY=mkdir in its environment. It will fail because $FILEPATH is a directory (if it exists) or at least not a command.



    To create a variable with spaces in its value, quote the value.



    The line



    if [ -e "${CREATE_COMMAND}" ]; then


    will not create a directory. It will test whether the value in $CREATE_COMMAND corresponds to a name in the file hierarchy.



    I don't know what error_exit is, but it's probably a shorthand for a simple echo and exit 1 or similar, right?






    share|improve this answer























      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "106"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f427078%2fhow-to-properly-test-a-command-as-a-variable-that-contains-spaces%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      I'm unsure why you would want to this, but here is a working solution:



      FILEPATH=/home/Documents/projectDirectory
      CREATE_DIRECTORY="mkdir $FILEPATH 2>/dev/null"
      eval $CREATE_DIRECTORY
      if [[ $? -eq 0 ]]; then
      echo "Directory created"
      else
      echo "Directory already exists"
      fi


      This will try to create the folder and pipe any error message to /dev/null (not displaying it). Then it checks the status of the previous command in the if statement and if that was successful (0) then tell you.






      share|improve this answer

















      • 1




        I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
        – Gordon Davisson
        Feb 28 at 6:40












      • I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
        – Mikael Kjær
        Feb 28 at 7:20















      up vote
      0
      down vote













      I'm unsure why you would want to this, but here is a working solution:



      FILEPATH=/home/Documents/projectDirectory
      CREATE_DIRECTORY="mkdir $FILEPATH 2>/dev/null"
      eval $CREATE_DIRECTORY
      if [[ $? -eq 0 ]]; then
      echo "Directory created"
      else
      echo "Directory already exists"
      fi


      This will try to create the folder and pipe any error message to /dev/null (not displaying it). Then it checks the status of the previous command in the if statement and if that was successful (0) then tell you.






      share|improve this answer

















      • 1




        I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
        – Gordon Davisson
        Feb 28 at 6:40












      • I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
        – Mikael Kjær
        Feb 28 at 7:20













      up vote
      0
      down vote










      up vote
      0
      down vote









      I'm unsure why you would want to this, but here is a working solution:



      FILEPATH=/home/Documents/projectDirectory
      CREATE_DIRECTORY="mkdir $FILEPATH 2>/dev/null"
      eval $CREATE_DIRECTORY
      if [[ $? -eq 0 ]]; then
      echo "Directory created"
      else
      echo "Directory already exists"
      fi


      This will try to create the folder and pipe any error message to /dev/null (not displaying it). Then it checks the status of the previous command in the if statement and if that was successful (0) then tell you.






      share|improve this answer












      I'm unsure why you would want to this, but here is a working solution:



      FILEPATH=/home/Documents/projectDirectory
      CREATE_DIRECTORY="mkdir $FILEPATH 2>/dev/null"
      eval $CREATE_DIRECTORY
      if [[ $? -eq 0 ]]; then
      echo "Directory created"
      else
      echo "Directory already exists"
      fi


      This will try to create the folder and pipe any error message to /dev/null (not displaying it). Then it checks the status of the previous command in the if statement and if that was successful (0) then tell you.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Feb 28 at 5:30









      Mikael Kjær

      44638




      44638








      • 1




        I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
        – Gordon Davisson
        Feb 28 at 6:40












      • I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
        – Mikael Kjær
        Feb 28 at 7:20














      • 1




        I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
        – Gordon Davisson
        Feb 28 at 6:40












      • I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
        – Mikael Kjær
        Feb 28 at 7:20








      1




      1




      I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
      – Gordon Davisson
      Feb 28 at 6:40






      I would not recommend using eval -- depending on how tightly controlled the contents of the command are, it's either unnecessary or unsafe or both. There are almost always better ways to do things (although what those better ways are depends on exactly what the actual problem is).
      – Gordon Davisson
      Feb 28 at 6:40














      I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
      – Mikael Kjær
      Feb 28 at 7:20




      I totally agree, but when we don't know the purpose of this script which doesn't make sense in it's current form it's very difficult to give a good answer.
      – Mikael Kjær
      Feb 28 at 7:20












      up vote
      0
      down vote













      Your current code has the following flaws:





      • CREATE_DIRECTORY=mkdir $FILEPATH:


        1. Since there are no quotes around mkdir $FILEPATH, CREATE_DIRECTORY only holds mkdir as its value.


        2. $FILEPATH is subject of word splitting.

        3. The CREATE_DIRECTORY variable may be exported to the environment of the resulting expansion of $FILEPATH if the first token of such expansion is an external command.




      • [ -e "${CREATE_COMMAND}" ]:


        1. The CREATE_COMMAND variable holds no value, as far as we know. I assume you meant to write CREATE_DIRECTORY.

        2. It doesn't test if mkdir was successful or not.




      Also, the if compound command could be used to test if a command succeeded or not:



      if command; then
      # Code to execute if command succeeded
      else
      # Code to execute if command failed
      fi


      So your code could be rewrite as:



      FILEPATH=/home/Documents/projectDirectory

      if [ -e "${FILEPATH}" ]; then
      echo "${FILEPATH} exists..."
      else
      if mkdir "${FILEPATH}"; then
      echo "File created ${FILEPATH}"
      else
      echo "Error creating the filePath..exiting.."
      error_exit "Error creating the filePath..exiting.."
      fi
      fi


      Note that:




      1. The CREATE_DIRECTORY variable is not needed.


      2. [ -e "${CREATE_COMMAND}" ] was replaced with mkdir "${FILEPATH}".






      share|improve this answer

























        up vote
        0
        down vote













        Your current code has the following flaws:





        • CREATE_DIRECTORY=mkdir $FILEPATH:


          1. Since there are no quotes around mkdir $FILEPATH, CREATE_DIRECTORY only holds mkdir as its value.


          2. $FILEPATH is subject of word splitting.

          3. The CREATE_DIRECTORY variable may be exported to the environment of the resulting expansion of $FILEPATH if the first token of such expansion is an external command.




        • [ -e "${CREATE_COMMAND}" ]:


          1. The CREATE_COMMAND variable holds no value, as far as we know. I assume you meant to write CREATE_DIRECTORY.

          2. It doesn't test if mkdir was successful or not.




        Also, the if compound command could be used to test if a command succeeded or not:



        if command; then
        # Code to execute if command succeeded
        else
        # Code to execute if command failed
        fi


        So your code could be rewrite as:



        FILEPATH=/home/Documents/projectDirectory

        if [ -e "${FILEPATH}" ]; then
        echo "${FILEPATH} exists..."
        else
        if mkdir "${FILEPATH}"; then
        echo "File created ${FILEPATH}"
        else
        echo "Error creating the filePath..exiting.."
        error_exit "Error creating the filePath..exiting.."
        fi
        fi


        Note that:




        1. The CREATE_DIRECTORY variable is not needed.


        2. [ -e "${CREATE_COMMAND}" ] was replaced with mkdir "${FILEPATH}".






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          Your current code has the following flaws:





          • CREATE_DIRECTORY=mkdir $FILEPATH:


            1. Since there are no quotes around mkdir $FILEPATH, CREATE_DIRECTORY only holds mkdir as its value.


            2. $FILEPATH is subject of word splitting.

            3. The CREATE_DIRECTORY variable may be exported to the environment of the resulting expansion of $FILEPATH if the first token of such expansion is an external command.




          • [ -e "${CREATE_COMMAND}" ]:


            1. The CREATE_COMMAND variable holds no value, as far as we know. I assume you meant to write CREATE_DIRECTORY.

            2. It doesn't test if mkdir was successful or not.




          Also, the if compound command could be used to test if a command succeeded or not:



          if command; then
          # Code to execute if command succeeded
          else
          # Code to execute if command failed
          fi


          So your code could be rewrite as:



          FILEPATH=/home/Documents/projectDirectory

          if [ -e "${FILEPATH}" ]; then
          echo "${FILEPATH} exists..."
          else
          if mkdir "${FILEPATH}"; then
          echo "File created ${FILEPATH}"
          else
          echo "Error creating the filePath..exiting.."
          error_exit "Error creating the filePath..exiting.."
          fi
          fi


          Note that:




          1. The CREATE_DIRECTORY variable is not needed.


          2. [ -e "${CREATE_COMMAND}" ] was replaced with mkdir "${FILEPATH}".






          share|improve this answer












          Your current code has the following flaws:





          • CREATE_DIRECTORY=mkdir $FILEPATH:


            1. Since there are no quotes around mkdir $FILEPATH, CREATE_DIRECTORY only holds mkdir as its value.


            2. $FILEPATH is subject of word splitting.

            3. The CREATE_DIRECTORY variable may be exported to the environment of the resulting expansion of $FILEPATH if the first token of such expansion is an external command.




          • [ -e "${CREATE_COMMAND}" ]:


            1. The CREATE_COMMAND variable holds no value, as far as we know. I assume you meant to write CREATE_DIRECTORY.

            2. It doesn't test if mkdir was successful or not.




          Also, the if compound command could be used to test if a command succeeded or not:



          if command; then
          # Code to execute if command succeeded
          else
          # Code to execute if command failed
          fi


          So your code could be rewrite as:



          FILEPATH=/home/Documents/projectDirectory

          if [ -e "${FILEPATH}" ]; then
          echo "${FILEPATH} exists..."
          else
          if mkdir "${FILEPATH}"; then
          echo "File created ${FILEPATH}"
          else
          echo "Error creating the filePath..exiting.."
          error_exit "Error creating the filePath..exiting.."
          fi
          fi


          Note that:




          1. The CREATE_DIRECTORY variable is not needed.


          2. [ -e "${CREATE_COMMAND}" ] was replaced with mkdir "${FILEPATH}".







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 28 at 6:52









          nxnev

          2,5482423




          2,5482423






















              up vote
              0
              down vote













              I don't really see why you can't just do



              dir='/home/Documents/projectDirectory'

              if ! mkdir "$dir"; then
              printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
              exit 1
              fi

              printf '"%s" created, now doing other things...n' "$dir"


              The call to mkdir will fail if $dir already exists.



              If you need to allow for the directory to exist and only bail out if mkdir fails to create it, then add -p to the mkdir call above, or do an explicit test for the existence of the directory:



              dir='/home/Documents/projectDirectory'

              if [ ! -d "$dir" ]; then
              if ! mkdir "$dir"; then
              printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
              exit 1
              fi

              printf '"%s" createdn' "$dir"
              fi

              echo 'now doing other things...'


              I'm using the -d test here to test whether $dir may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.





              Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.



              Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.



              Related:




              • Why does my shell script choke on whitespace or other special characters?

              • How can we run a command stored in a variable?




              Other things:



              CREATE_DIRECTORY=mkdir $FILEPATH


              This will run $FILEPATH as a command with CREATE_DIRECTORY=mkdir in its environment. It will fail because $FILEPATH is a directory (if it exists) or at least not a command.



              To create a variable with spaces in its value, quote the value.



              The line



              if [ -e "${CREATE_COMMAND}" ]; then


              will not create a directory. It will test whether the value in $CREATE_COMMAND corresponds to a name in the file hierarchy.



              I don't know what error_exit is, but it's probably a shorthand for a simple echo and exit 1 or similar, right?






              share|improve this answer



























                up vote
                0
                down vote













                I don't really see why you can't just do



                dir='/home/Documents/projectDirectory'

                if ! mkdir "$dir"; then
                printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                exit 1
                fi

                printf '"%s" created, now doing other things...n' "$dir"


                The call to mkdir will fail if $dir already exists.



                If you need to allow for the directory to exist and only bail out if mkdir fails to create it, then add -p to the mkdir call above, or do an explicit test for the existence of the directory:



                dir='/home/Documents/projectDirectory'

                if [ ! -d "$dir" ]; then
                if ! mkdir "$dir"; then
                printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                exit 1
                fi

                printf '"%s" createdn' "$dir"
                fi

                echo 'now doing other things...'


                I'm using the -d test here to test whether $dir may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.





                Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.



                Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.



                Related:




                • Why does my shell script choke on whitespace or other special characters?

                • How can we run a command stored in a variable?




                Other things:



                CREATE_DIRECTORY=mkdir $FILEPATH


                This will run $FILEPATH as a command with CREATE_DIRECTORY=mkdir in its environment. It will fail because $FILEPATH is a directory (if it exists) or at least not a command.



                To create a variable with spaces in its value, quote the value.



                The line



                if [ -e "${CREATE_COMMAND}" ]; then


                will not create a directory. It will test whether the value in $CREATE_COMMAND corresponds to a name in the file hierarchy.



                I don't know what error_exit is, but it's probably a shorthand for a simple echo and exit 1 or similar, right?






                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I don't really see why you can't just do



                  dir='/home/Documents/projectDirectory'

                  if ! mkdir "$dir"; then
                  printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                  exit 1
                  fi

                  printf '"%s" created, now doing other things...n' "$dir"


                  The call to mkdir will fail if $dir already exists.



                  If you need to allow for the directory to exist and only bail out if mkdir fails to create it, then add -p to the mkdir call above, or do an explicit test for the existence of the directory:



                  dir='/home/Documents/projectDirectory'

                  if [ ! -d "$dir" ]; then
                  if ! mkdir "$dir"; then
                  printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                  exit 1
                  fi

                  printf '"%s" createdn' "$dir"
                  fi

                  echo 'now doing other things...'


                  I'm using the -d test here to test whether $dir may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.





                  Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.



                  Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.



                  Related:




                  • Why does my shell script choke on whitespace or other special characters?

                  • How can we run a command stored in a variable?




                  Other things:



                  CREATE_DIRECTORY=mkdir $FILEPATH


                  This will run $FILEPATH as a command with CREATE_DIRECTORY=mkdir in its environment. It will fail because $FILEPATH is a directory (if it exists) or at least not a command.



                  To create a variable with spaces in its value, quote the value.



                  The line



                  if [ -e "${CREATE_COMMAND}" ]; then


                  will not create a directory. It will test whether the value in $CREATE_COMMAND corresponds to a name in the file hierarchy.



                  I don't know what error_exit is, but it's probably a shorthand for a simple echo and exit 1 or similar, right?






                  share|improve this answer














                  I don't really see why you can't just do



                  dir='/home/Documents/projectDirectory'

                  if ! mkdir "$dir"; then
                  printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                  exit 1
                  fi

                  printf '"%s" created, now doing other things...n' "$dir"


                  The call to mkdir will fail if $dir already exists.



                  If you need to allow for the directory to exist and only bail out if mkdir fails to create it, then add -p to the mkdir call above, or do an explicit test for the existence of the directory:



                  dir='/home/Documents/projectDirectory'

                  if [ ! -d "$dir" ]; then
                  if ! mkdir "$dir"; then
                  printf 'Something went wrong when trying to create "%s"n' "$dir" >&2
                  exit 1
                  fi

                  printf '"%s" createdn' "$dir"
                  fi

                  echo 'now doing other things...'


                  I'm using the -d test here to test whether $dir may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.





                  Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.



                  Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.



                  Related:




                  • Why does my shell script choke on whitespace or other special characters?

                  • How can we run a command stored in a variable?




                  Other things:



                  CREATE_DIRECTORY=mkdir $FILEPATH


                  This will run $FILEPATH as a command with CREATE_DIRECTORY=mkdir in its environment. It will fail because $FILEPATH is a directory (if it exists) or at least not a command.



                  To create a variable with spaces in its value, quote the value.



                  The line



                  if [ -e "${CREATE_COMMAND}" ]; then


                  will not create a directory. It will test whether the value in $CREATE_COMMAND corresponds to a name in the file hierarchy.



                  I don't know what error_exit is, but it's probably a shorthand for a simple echo and exit 1 or similar, right?







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 25 at 14:56

























                  answered Feb 28 at 6:55









                  Kusalananda

                  117k16221360




                  117k16221360






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f427078%2fhow-to-properly-test-a-command-as-a-variable-that-contains-spaces%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Accessing regular linux commands in Huawei's Dopra Linux

                      Can't connect RFCOMM socket: Host is down

                      Kernel panic - not syncing: Fatal Exception in Interrupt