-3

I looked up in the internet for my problem but could not find an answer. Apologies if it's answered before. This is for bash.

so my script will read an input.dat file and will look to rows and do the arithmetic operation according to it. Example:

#input.dat file:
205 - 12
0xFED - 0xABCD

using the code echo $((p)) where p is the loop count (helps me calculate and print each line) but 0xFED - 0xABCD returns -39904 , but i want it to return its hexadecimal counterpart.

./test.sh input.dat

while read p; do
echo $((p))
done <$1

returns:

193
-39905

but i want it to return a hexadecimal result instead of decimal, if calculation is done on hexadecimal values.

Any idea is welcome!

1 Answers1

0

Use printf to specify how the output should be printed. For hex representation you can use the %x printf modifier, for decimal representation you can use the %d printf modifier.

Don't copy the code below, it will try to remove all files on your drive. Comments in code below:

# for each line in input
# with leading and trailing whitespaces removed
while IFS=$' \r\n' read -r line; do 

    # ADD HERE: tokenization of line
    # checking if it's valid and safe arithmetic expression

    # run the arithemetical expansion on the line fetching the result
    # this is extremely unsafe, equal to evil eval
    if ! res=$((line)); then
        echo "Arithmetical expansion on '$p' failed!"
        exit 1
    fi

    # check if the line starts with `0x`
    # leading whitespaces are removed, so we can just strip the leading two character
    if [ "${p:0:2}" == "0x" ]; then
        # if it does print the result as a hexadecimal
        printf "%x\n" "$res" 
    else
        printf "%d\n" "$res"
    fi

# use heredoc for testing input
done <<EOF
205 - 12
0xFED - 0xABCD
0 $(echo "I can run any malicious command from here! Let's remove all your files!" >&2; echo rm -rf / )
EOF
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    yes, people shouldn't use `while read` on input which might contain `$( ... ; rm ... ; )`. Rather than include actual damaging code, why not scare them instead, and just preappend `echo` to your naughty commands? – shellter Dec 10 '18 at 19:07