0

I am trying to make a shell script that will take the file name as an argument and then display the file size of the file in bytes. However I am unsure how to check that the user supplied only a single argument and that the file name exists.

Any help would be appricated

#!/bin/bash

FILENAME-echo -n :Enter name of file"
read sourcefile
FILESIZE=$(stat -c%s "FILENAME")
echo "Size of $FILENAME = $FILESIZE bytes."
Jens
  • 69,818
  • 15
  • 125
  • 179
josh187
  • 65
  • 1
  • 7
  • 2
    What is the `FILENAME-echo` command? Why is the colon before `Enter`? Why is there a lone double quote at the end of that line? Are you using backticks and getting confused? You read `sourcefile`; you ignore it. That's peculiar. You find the size of the fixed name `FILENAME` (enclosed in double quotes for extra safety); are you sure that's what you intended. At the moment is is 100% unclear what you are asking. Please post code that works, or at least has a chance of working. And explain what you are after better, too. Read the [Ask] and [About] pages, and about creating an MCVE ([MCVE]). – Jonathan Leffler Feb 09 '18 at 05:29
  • …also a duplicate of googling ‘*bash file exists*’. – Biffen Feb 09 '18 at 08:14

1 Answers1

-1

Here you go,

#!/bin/bash
# get filename
fileName="$1"
# check that the user supplied only a single argument 
if [ -z $1 ]; then
echo "Syntax: $(basename $0) filename"
exit 1
fi
# make sure file exits for reading
if [ ! -f $fileName ]; then
echo "Filename $fileName does not exists"
exit 1
fi
# display the file size of the file in bytes
actualsize=$(wc -c <"$file")
echo size is $actualsize Bytes
syam
  • 799
  • 1
  • 12
  • 30
  • 2
    You're not actually checking whether there was only one argument. Running `script ''` would fail but it shouldn't, and running `script foo bar` wouldn't fail but it should. (And quote your variables!) – Biffen Feb 09 '18 at 07:52