Archivi tag: ksh

La variabile IFS di read

La variabile di sistema IFS viene utilizzato dal comando read per identificare il carattere divisore di un file csv.

Ecco un esempio per gestire un csv di input.
cat input_test.txt | while IFS=',' read campo1 campo2 campo3
echo "campo1 -> $campo1 ; campo2 -> $campo2 ; campo3 -> $campo3 "

Utilizzando il seguente “input_test.txt”….


…otteniamo il seguente output

# sh
campo1 -> a ; campo2 -> b ; campo3 -> c
campo1 -> 1 ; campo2 -> 2 ; campo3 -> 3
campo1 -> primo ; campo2 -> secondo ; campo3 -> terzo

Contrassegnato da tag , , , , , , , ,

Inserire FTP in uno script ksh

#! /usr/bin/ksh

exec 4>&1
ftp -nv >&4 2>&4 |&

print -p open $HOST
print -p user $USER $PASSWD
print -p cd directory
print -p binary
print -p put tar.gz
print -p bye

exit 0

That is the file descriptor manipulation. Recall that fd 0 is standard-in, fd 1 is standard-out, and fd 2 is standard-error. The line “exec 4&>1” opens fd 4 and assigns it to whatever fd 1 was assigned to. As you will see, I am sorta “saving a copy of fd 1 in fd 4”. The line “ftp -nv >&4 2>&1 |&” is a little harder. The “|&” turns the process into a co-process that allows subsequent “print -p” statements to send lines to the co-process’ standard-in and “read -p” to read from its standard-out. So ksh forks a copy of itself and fiddles with the fd’s 0 and 1 until this it set-up. But it leaves the rest of the fd’s alone. Then it encounters “>&4” which causes it to set the ftp process’ standard out to whatever 4 is. Well since 4 is a copy of 1 before the co-process, we are back to writing to the original shell’s standard out. Lastly, the 2>&4 does the same thing for standard error. I could’ve used “2>&1” at this point for the same effect. This is hard to explain, but I hope this helps.

Contrassegnato da tag , , ,

Array in ksh

Gli array in ksh si gestiscono cosí:

# set -A MyArray campo1 campo2 campo3
# echo ${MyArray[0]}
# for i in ${MyArray[@]}
> do
> echo $i
> done

Contrassegnato da tag , , ,