3

I want to separate a long path to multiple lines, like this:

cd foo1/foo2/foo3/foo4/bar

to

cd foo1\
   foo2\
   foo3\
   foo4\
   bar
2
  • 2
    Did you want the backslashes (\) to turn into forward slashes (/) automatically? Commented Mar 18, 2021 at 13:10
  • yes but Backlash and antislash give me errore : cd: too many arguments Commented Mar 18, 2021 at 13:12

2 Answers 2

11

You can separate a long command into multiple lines by using backslashes, but you would need to preserve the forward-slashes and omit the leading spaces:

cd foo1\
/foo2\
/foo3\
/foo4\
/bar

The backslashes are a line-continuation marker; when bash sees them, it incorporates the next line as if it was continued at the backslash of the current line. As a result, you couldn't use leading spaces on those subsequent lines, since they'd become spaces on the current line, creating a "too many arguments" error.

2
  • i like it , but can i have indent Commented Mar 18, 2021 at 13:20
  • 3
    @AyoubElMhamdi No you can't have an indent. Commented Mar 18, 2021 at 13:20
2

You could do this with an array but the cd command looks a bit complicated:

path=(
    foo1
    foo2
    foo3
    foo4
    bar
)
cd "$(IFS=/; echo "${path[*]}")"

Array literals allow for arbitrary whitespace.

5
  • that is better for indente, can you explain IFS meen Commented Mar 19, 2021 at 0:05
  • 1
    The "$*" and "${array[*]}" forms, when in double quotes, join all the elements into a single string, joined by the first character of the IFS variable. IFS is, by default, "space tab newline", so I redefine it in the subshell to hold the directory separator. Commented Mar 19, 2021 at 15:18
  • wow, i see some Magic here, it's perfect Mr @glenn-jackman Commented Mar 21, 2021 at 1:38
  • donc ,you are using IFS to trim whitespace ? and converte to "/" Commented Mar 21, 2021 at 1:41
  • 1
    The array contains 5 elements with no extra whitespace. You can inspect the array using declare -p path. "${path[*]}" joins the elements into a single string using /, the first character of IFS. Commented Mar 21, 2021 at 12:03

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.