1

my script hex.sh

#!/bin/sh
if [ -f $file_name ]
then do 
 cat[$file_name] | xxd -r -p
 else 
echo "$file_name not exists"
fi

The file must either be an existing file or '-' to read from the standard input.


The result should be :

./hex.sh test_number
017 AAA

test_number might contain :

30  31  37  20  41  41  41  20  0A
1

I came up with the following for this:

#!/bin/sh

if [ "$1" = '-' ]; then
    file='/dev/stdin'
else
    if [ ! -f "$1" ]; then
        printf 'ERROR! Cannot find file\n' >&2
        exit 1
    else
        file=$1
    fi
fi

while read -r num; do
    printf '%s\n' "$num" | xxd -r -p
    echo
done < "$file"
  • If the first positional parameter is - we will read from stdin
  • Otherwise we check if the first argument is a valid file. If it is we will read from it, if not we will error and exit.
  • We will read each line either from stdin or the file and set the line to the num variable
  • we will pass the num variable to xxd to convert it
  • echo here to ensure a newline is added after each result

With file:

$ cat test_number
30  31  37  20  41  41  41  20  0A
30  31  37  20  41  41  41
30 31 37 20 42 42 42
30 31 37 20 43 43 43
42 45 45 46
$ ./hex.sh test_number
017 AAA

017 AAA
017 BBB
017 CCC
BEEF

From stdin:

$ ./hex.sh -
30  31  37  20  41  41  41  20  0A
017 AAA

42 45 45 46
BEEF
^C
$
  • @ZPUFF19: I'm not sure if you are asking a question or making a statement. If you need to change your requirements please edit your question or ask another. – Jesse_b Mar 27 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.