###################################################################### # USAGE: CreateHexFile FILENAME [LIST] # This function creates a binary file and writes some bytes in it. # The first argument should be the full name of the file to be # created. The following arguments must be pairs of hexadecimal # digits which are converted to bytes and written to the file. # Finally, the function creates a global variable named $SUCCESS # and will write the number of bytes written into this variable. # If an error occurs, then this variable will hold an empty string. # If the function was called with only one argument, meaning that # no bytes were expected to be written, then the function will # create a file and leave it blank, and $SUCCESS will be set to 0. # # Example: # # CreateHexFile "myfile.tmp" 00 c3 9d 80 7e 92 23 ff 00 2c # if [[ $SUCCESS ]]; then # echo "$SUCCESS bytes written successfully." # else # echo "Failed to create file." # fi # function CreateHexFile { SUCCESS='' local filename="$1" local bytecount=0 local byte local hex shift # Create the file > "$filename" # File exists? if [[ -f $filename ]]; then # Make sure file length is zero at this point: local filelen=$(stat --printf="%s" "$filename") if [[ $filelen -gt 0 ]]; then return 0 fi SUCCESS=0 # Convert hexadecimal numbers to bytes # and write them to the file: for hex in "$@"; do # Remove everything except hexadecimal digits hex=$(printf '%s' "${hex//[![:xdigit:]]}") for (( i=0; i<${#hex}; i+=2 )); do # Take two digits at a time byte="\\x${hex:i:2}" # Write it to the file one byte at a time printf "$byte" >> "$filename" # Count number of bytes sent to the file bytecount=$((bytecount + 1)) done done if [[ $bytecount -gt 0 ]]; then local filelen=$(stat --printf="%s" "$filename") if [[ $filelen -eq $bytecount ]]; then SUCCESS=$filelen fi fi else echo "Error: Cannot create file - $filename" >&2 fi } $MyList = " 00 01 02 03 04 05 06 07 " CreateHexFile "ASCIIBASH.BIN" $MyList