How to Handle Spaces in Arguments for My Bash Function?

0
24
Asked By CuriousCoder42 On

Hey there! I created a function in my `.bashrc` that uses the `tree` command. Here's what it looks like:
```
function mytree {
/usr/bin/tree -C $* | less -R -S
}
```
This works fine if none of my arguments have spaces. However, when I tried quoting the arguments with `"$*"`, it allowed directory paths with spaces, but messed up passing options. For instance, when I run `mytree -L 2 "/dir/with spaces"`, it incorrectly interprets it as two separate arguments: `"/dir/with/"` and `spaces/`.

Is there a solution to this? I need to be able to pass both options and directory names that include spaces. And please, don't suggest renaming my directories; I often need to use similar functions on work servers.

5 Answers

Answered By SyntaxSam On

Yeah, definitely go with `"$@"`. It handles arguments much better and maintains their individual integrity. Good luck!

Answered By TechieTim On

To fix your issue, you should use `"$@"` instead of `"$*"`. The `"$@"` format keeps each argument separate, preserving spaces correctly. Just make sure to include the quotes!

Answered By BashBot174 On

Glad I could help! Switching to `"$@"` worked for you, right?

Answered By CommandLineNinja On

Try using `"$@"`, it should solve your problem with spaces in the arguments.

Answered By DocuMentor On

"$@" is definitely the way to go here. Just make sure to read up on it; it'll make your bash life a lot easier!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.