LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Scripting help needed (https://www.linuxquestions.org/questions/linux-newbie-8/scripting-help-needed-881742/)

pinga123 05-20-2011 02:27 AM

Scripting help needed
 
For getting individual entries from $PATH variable i m using following scrip let.
Code:

#!/bin/bash

COUNT=`echo "$PATH" | awk -F ":" '{print NF}'`
while [ "$COUNT" -ge 1 ]
do
echo "$PATH" | awk -v m=$COUNT -F ":" '{print "ls -ld " $m}'|sh
COUNT=`expr $COUNT - 1`
done

Is there any other way of doing it ?

colucix 05-20-2011 02:35 AM

Yes. You can either do anything from awk or use pure bash. The latter will look like this:
Code:

#!/bin/bash
OLD_IFS="$IFS"

IFS=":"
for dir in $PATH
do
  ls -ld $dir
done

IFS="$OLD_IFS"

This take advantage from the fact you can change the input field separator, so that the for loop iterates over the colon separated list of directories. The OLD_IFS stuff serves to save and restore the default value before and after the loop respectively.

catkin 05-20-2011 03:04 AM

Hello colucix :)

As a variation on the same (at the expense of using a subshell, avoids need to save and restore IFS):
Code:

( export IFS=':'; for dir in $PATH; do ls -ld $dir; done )
EDIT:

It could more simply be:
Code:

( IFS=':'; for dir in $PATH; do ls -ld $dir; done )

colucix 05-20-2011 03:15 AM

Hello catkin! :)

That's a nice idea (I always hated this OLD_IFS stuff)! Something to take in mind as future reference.

grail 05-20-2011 04:21 AM

How about we just make it easy and leave IFS alone :)
Code:

for dir in ${PATH//:/ }; do ls -ld $dir; done

colucix 05-20-2011 04:27 AM

Hi grail! :) That's right! Another nice solution.

grail 05-20-2011 04:50 AM

Actually, I assume something else must be going to be done in the loop as the substituion could just be used with the ls on its own:
Code:

ls -ld ${PATH//:/ }

catkin 05-20-2011 06:15 AM

Quote:

Originally Posted by grail (Post 4361701)
Actually, I assume something else must be going to be done in the loop as the substituion could just be used with the ls on its own:
Code:

ls -ld ${PATH//:/ }

Neat :)


All times are GMT -5. The time now is 06:05 AM.