views:

43

answers:

1

Within a loop in my bash script, I am 'doing work', then writing the result of each iteration to its own file. I'd like to name these files

# User-defined Function (UDF)
processLine(){

line="$@" # get all args 
index=$(echo $line | gawk -F::: '{ print $1 }')
content=$(echo $line | gawk -F::: '{ print $2 }')

# Let's tr it to remove double-quotes(42) and lfs(12)!
content=$(echo $content | tr -d \012)
content=$(echo $content | tr -d \042)
content=$(echo $content | tr -d \054)

# - THEN APPEND THE LINE to OUTPUT FILE
echo $index','$content>>OUTPUT

# - ALSO, save 'raw' individual student data as a backup
echo $content>STUDENTS/STUDENT.$index
}

Yes, I know, that tr stuff is poorly written! Hey, it's almost my first script!

I'd like to write filenames like STUDENT.7534, not STUDENT."7534" - which can't even be opened.

Hmmm... What to do?

+3  A: 

Critique:

# User-defined Function (UDF)
processLine(){

    index=$1  # First argument is the index
    shift     # Remove the index
    # Grab the content - "$*" is fine here,
    # and $* or $@ without quotes would probably work
    # And do the editing in a single tr operation
    # And document what we're doing completely
    # Let's tr it to remove double-quotes (42) and lfs (12) and comma (54)!
    content=$(echo "$*" | tr -d \012\042\054)

    # - THEN APPEND THE LINE to OUTPUT FILE
    # Single quotes around the comma are unnecessary
    echo $index,$content >>OUTPUT

    # - ALSO, save 'raw' individual student data as a backup
    echo $content >STUDENTS/STUDENT.$index
}

There is nothing in this which adds (or removes) double quotes in the index - so the call to this code must be putting the quotes there.

You say the output file name is:

STUDENT."7534" - which can't even be opened.

It can be opened as long as you remember that the shell removes double quotes, so you have to stop it doing so:

cat 'STUDENT."7534"'

All you have to do is persuade your instructors that it is a security precaution to ensure they know enough shell to be able to access your protected files.

Jonathan Leffler
If the function is being called with quotes around the first parameter, you can set `index=$(echo $index | tr -d '"')` to strip the quotes before building the filename.
bta
@bta: agreed, but it is generally easier to make sure the quotes aren't passed to the function in the first place. Hence the request for 'how is it called', not least because it takes some doing. For example, `processLine "$studentid" "$other_info"` does not pass any double quotes to `processLine` unless they were already in the value stored in `$studentid`...which punts the issues to how that part of the script is working. If a function gets called with bogus data, it is better to fix the caller than to fix the function, unless there are compelling reasons not to change the caller.
Jonathan Leffler