Need some bash scripting help

This works as intended:

ln -s /path/to\ somewhere/dir/* /path/to/elsewhere/

(it creates symbolic links to everything inside one directory within another directory)

This does not work as intended:

location="/path/to\ somewhere/"
ln -s $location/dir/* /path/to/elsewhere/

I’ve tried various ways to make it work, but I can’t seem to figure it out.

I need the path to be a variable so I can change it easily, but I can’t figure out how to make that work out.

For one thing, what is the shebang?
(the header beginning with #!)
This could affect how things are parsed.
For another … quoting is often a good idea if you want to preserve something like an environment variable. ex:

ln -s "$location"/dir/* /path/to/elsewhere/
1 Like

Thanks! It worked!

(Also, shebang was directed at bash, hence bash tag)

Oh actually it didn’t work. When I said it just gave me a symlink called * i thought i’d just forgotten to refresh but it was because i probably forgot to save or something (had it configured for the hardcoded path before save).

But I manged to fix it. In order for it to work it must be like this:

location="/path/to somewhere/"
ln -s "$location"/dir/* /path/to/elsewhere/

(it didn’t work if there was a backslash)

Ah, yes … the quoting of the backslash in the original would be carried over and read as an actual character.
Whereas quoting with the space retains the space with no need for the slash.

Bash scripting is often a bit like puzzling lol, you wrangle the syntax trying different ways to tell it to do the same thing until it does what you want or you give up on it and ask for help :joy:

I have made so many scripts of such varying degrees of complexity, but there’s always something that i forget how to do by the time i write the next script.

1 Like

I suppose it can be an example though.
Of why we generally avoid spaces in filename or directories.
Its common in the windoze world, along with other things like ignoring cAsEs, but here a space is often a separator and may need to be ‘escaped’ as you have already encountered.

Yeah, I like to keep my system files structured for console readability and the rest structured for human readability, which means spaces, it just looks prettier.

Sometimes that leads to shenanigans like these, but it’s important to know how to do it because a lot of scripts I couldn’t make work if i didn’t know how to work around spaces, for instance you can never really know if a filename that needs to be passed through to a script on a file by file basis will have a space or not, man it took me a while to work around that one too.

How shells handle spaces is inconvenient as hell, but it’s not like there’s a known better way, because we still need to be able to use them to separate arguments.

This topic was automatically closed 3 hours after the last reply. New replies are no longer allowed.