Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through the elements of a path variable in Bash

Tags:

linux

bash

I want to loop through a path list that I have gotten from an echo $VARIABLE command.

For example:

echo $MANPATH will return

/usr/lib:/usr/sfw/lib:/usr/info

So that is three different paths, each separated by a colon. I want to loop though each of those paths. Is there a way to do that? Thanks.

Thanks for all the replies so far, it looks like I actually don't need a loop after all. I just need a way to take out the colon so I can run one ls command on those three paths.

like image 692
tim tran Avatar asked Jul 25 '12 17:07

tim tran


People also ask

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

What does %% do in bash?

In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.

How do I set the PATH variable in bash?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/. bashrc, or ~/.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

You can set the Internal Field Separator:

( IFS=:   for p in $MANPATH; do       echo "$p"   done ) 

I used a subshell so the change in IFS is not reflected in my current shell.

like image 86
choroba Avatar answered Oct 11 '22 15:10

choroba