Score:0

How to "cd $variable" when the variable tries to add "\" before spaces (path contain spaces)?

cn flag

My bash script registers its own path so it can return to its own folder after doing a cd somewhere (kinda if it explores a different forest and is able to relocate its house).

And if the path have spaces, I've used sed to add \ before every space.

But when using cd $SCRIPTPATH to this variable:

./newsed.sh: 11: cd: can't cd to /media/daniell/B/bkp/ST500LM012\

Source: newsed.sh:

#!/bin/bash -e

tmp="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
SCRIPTPATH="$(echo "$tmp" | sed 's/ /\\ /g')"

echo "$SCRIPTPATH"

ls
cd
ls
cd $SCRIPTPATH
ls

echo $SCRIPTPATH produces a normal path (/media/daniell/B/bkp/ST500LM012\ HN-M500MBB\ Dat/0/ok/Pendrive/flshdrive/0.Floflis-DNA/layers/soil) that I can manually copy and cd into it, and works; but when cd'ing directly to the variable (cd $SCRIPTPATH) it crashes right after the \.

hr flag
*"And if the path have spaces, I've used sed to add \ before every space."* you can avoid the need to do that altogether by quoting the variable expansion properly ex. `cd "$variable"`
cn flag
@steeldriver Thank you, the output have improved. But: `./newsed.sh: 11: cd: can't cd to /media/daniell/B/bkp/ST500LM012\ HN-M500MBB\ Dat/0/ok/Pendrive/flshdrive/0.Floflis-DNA/layers/soil` ?
hr flag
Are you still escaping the spaces with backslashes with sed? If so - don't.
cn flag
@steeldriver Gotcha! Thanks a lot. If you turn your comments into a answer, I'll mark it as correct/best answer.
waltinator avatar
it flag
Don't bother with escaping spaces, simply quote the variable expansion: `cd "$tmp"`.
Score:0
cn flag

Use quotes around variables to prevent spaces from being treated as delimiters in the shell, i.e.

cd "$SCRIPTPATH"

will work.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.