Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: passing paths with spaces as parameters?

Tags:

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?

like image 407
fbrereto Avatar asked Sep 23 '11 22:09

fbrereto


People also ask

How do I handle a space in a bash path?

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.

How do you pass a space in a bash script?

Save this question. In a bash script, we can escape spaces with \ .

Can Linux paths have spaces?

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.

How do you create an argument which contains a space inside it?

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.


1 Answers

#! /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.

like image 153
Roland Illig Avatar answered Sep 25 '22 12:09

Roland Illig