I have a bash script that recieves a set of files from the user. These files are sometimes under directories with spaces in their names. Unfortunately unlike this question all the filenames are passed via the command line interface. Let's assume the paths are correctly quoted as they are passed in by the user, so spaces (save for quoted spaces) are delimiters between paths. How would I forward these parameters to a subroutine within my bash script in a way that preserves the quoted spaces?
To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.
Save this question. In a bash script, we can escape spaces with \ .
In the Linux operating system, we can run commands by passing multiple arguments. A space separates each argument. So, if we give the path that has a space, it will be considered two different arguments instead of one a single path.
Argument values that contain a space in it have to be surrounded by quotes in order to be properly parsed by sys . The equivalent of argc is just the number of elements in the list. To obtain this value, use the Python len() operator.
#! /bin/bash for fname in "$@"; do process-one-file-at-a-time "$fname" done
Note the excessive use of quotes. It's all necessary.
Passing all the arguments to another program is even simpler:
process-all-together "$@"
The tricky case is when you want to split the arguments in half. That requires a lot more code in a simple POSIX shell. But maybe the Bash has some special features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With