|
||||||
| Forums FAQ | Members List | Search | Today's Posts | Mark Forums Read |
| ARCHIVES - Programming & Scripting A place to discuss website design, programming, shell scripts, etc |
|
|
LinkBack | Thread Tools | Display Modes |
|
|||
|
I wrote this simple script :
#!/bin/bash cnf=X ls *.cnf* > toto.txt N=0 cat toto.txt | while read LINE ; do N=$((N+1)) exten=${LINE##*.} case $exten in cnf1) cnf=Y ;; cnf2) ..... ;; esac echo "$cnf" ; This displays Y when the condition is met done echo "$cnf" : This always display X whatever happened in the loop I tried to export, declare ..... still the same. I am not familiar with linux but still feel able to handle this kind of stuff at the condition I can get the value after the loop... Its maybe a very beginner question but I did nt get any answer in my readings if anybody can help... |
|
|||
|
I can't reproduce your problem but your script is unnecessarily complex.
You can just do: Quote:
|
|
|||
|
Quote:
I tried your way and it works like a charm. A very big thanks. I'll try when i will be a bit less pressured to put my old code in a lab to understand this weird behavior even if its a weird code
|
|
|||
|
Actually I think I know what your problem is. When you do
cat toto.txt | while read LINE do done you are running the while in a different shell instance because of the piping and redirection, so the variable there will belong to that shell not to the outer one. But this should work: for LINE in $(cat toto.txt) do done or better still, what I showed you, forget about the intermediate file toto.txt. |
|
|||
|
Ironically I hit this same issue yesterday using "while" instead of "for"
I actually only need the final answer from the entire thing, so what I did was pipe all to "tail -1" and then run the whole lot in a seperate shell with the output going into a variable, a very messy way of doing it, but it worked for me, I might try some of these other ways though. as you're using Bash, there is a work-around (unfortunately all my scripts are written in Korn Shell, which doesn't have this work-around) this is how I would do this in Bash: Code:
#!/bin/bash
cnf=X
ls *.cnf* > toto.txt
N=0
while read LINE; do
N=$((N+1))
exten=${LINE##*.}
case $exten in
cnf1) cnf=Y;;
cnf2) .....;;
esac
echo "$cnf"; This displays Y when the condition is met
done < <(cat toto.txt)
echo "$cnf" : This always display X whatever happened in the loop
This is Bash's work-around for this problem of course, everyone has their own ways of doing these scripts, this is generally mine when I'm using bash. Jason. |
| Bookmarks |
| Thread Tools | |
| Display Modes | |
|
|