0

Here is the Problem Description:

I am having a very strange issue with a bash script invoking an 'ln' command. I build the command in the script, and then print the command to stdout, and then invoke the command. (Code follows)...

If I copy what gets printed to the console and paste it and execute it directly in the command line, it does what I expect it to do without error. However, when the exact same command is issued from within the bash script it fails with a "No such file or directory" error on the target. (There are no spaces in either the source or the target paths. This makes no sense!

Does anyone here have an explanation for this behavior, and a solution?

Thanks!

Here is the code:

#!/bin/bash

sourcePath=~/temp
destPath=~/_screensaver_
mkdir -p ${sourcePath}
lnCmd="ln -s -v -f \"${sourcePath}\" \"${destPath}\""

if [[ ! -d ${sourcePath} ]]; then
    #
    # Check to see that all of the required directories are there
    #
    errCode="Directory \"${sourcePath}\" does not exist"
fi

if [[ -L ${destPath} ]]; then
    echo "${destPath} EXISTS"
else
    echo "${destPath} DOES NOT EXIST"
fi

#
# Execute the command and check for errors
#
echo "Executing: ${lnCmd}"
errCode=$(${lnCmd} 2>&1)
retCode=$?

if [[ "X${retCode}" != "X0" ]]; then
    echo "FAILED: ${errCode}"
else
    echo "SUCCESS"
fi
rmdir ${sourcePath}`

Here is the output:

/Users/mbi/_screensaver_ DOES NOT EXIST
Executing: ln -s -v -f "/Users/mbi/temp" "/Users/mbi/_screensaver_"
FAILED: ln: "/Users/mbi/_screensaver_": No such file or directory

I expected this to succeed without an error.

fiddleman
  • 1
  • 2
  • 4
    https://mywiki.wooledge.org/BashFAQ/050 – KamilCuk Jun 03 '23 at 18:06
  • 2
    Please paste your script at [shellcheck.net](http://www.shellcheck.net/) and try to implement the recommendations made there. – Cyrus Jun 03 '23 at 18:12
  • 2
    Don't store commands in variables unless you really really need to for some reason. Variables are for storing data, not executable code; that's what functions are for. If you really need to build a command in a variable, use an array instead of a plain variable. – Gordon Davisson Jun 03 '23 at 19:05

1 Answers1

2

Does anyone here have an explanation for this behavior

Word splitting expansion does not interpret quotes.

a solution?

Use bash array. Do not store commands in a variable. Use shellcheck to check your code.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111