0

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
  • 1
    Did you want the backslashes (\) to turn into forward slashes (/) automatically?
    – Jeff Schaller
    Mar 18 at 13:10
  • yes but Backlash and antislash give me errore : cd: too many arguments
    – nextloop
    Mar 18 at 13:12
7

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.

3
  • i like it , but can i have indent
    – nextloop
    Mar 18 at 13:20
  • 2
    @AyoubElMhamdi No you can't have an indent.
    – Kusalananda
    Mar 18 at 13:20
  • thank you so mush @JeffSchaller
    – nextloop
    Mar 18 at 13:23
1

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
    – nextloop
    Mar 19 at 0:05
  • 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. Mar 19 at 15:18
  • wow, i see some Magic here, it's perfect Mr @glenn-jackman
    – nextloop
    Mar 21 at 1:38
  • donc ,you are using IFS to trim whitespace ? and converte to "/"
    – nextloop
    Mar 21 at 1:41
  • 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. Mar 21 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.