0

I'm working on a bash script and for a part of the bash script I want to take the most recent file in a directory and make a new file in the same directory , but the new file should be increased by one. So for example if the most recent file is file1234.txt I want to create a new file in the directory called file1235.txt. So my code is as follows.

file=$(ls -ltr /home/dir |tail -n 1 | awk '{print $9}'  | cut -f1 -d "." | cut -c 5- )
echo $file

newfile=$((file +1 ))
echo $newfile
touch file$newfile.txt

The issue is that the new file that is created is file1.txt not file1235.txt. Is this an issue with subshells being created?

manhasnoname
  • 123
  • 2
  • 2
  • 11
  • If you really want to [parse `ls`](https://mywiki.wooledge.org/ParsingLs) then check if `ls -ltr /home/dir |tail -n 1` prints what you expect in the format you expect. Maybe there is an unrelated file ([possibly directory](https://superuser.com/a/1467109/432690)) that is most recent at the moment. – Kamil Maciorowski Mar 03 '21 at 22:29
  • I can't reproduce: `cd "$(mktemp --directory)" && touch file123.txt && touch file1234.txt && file=$(ls -ltr |tail -n 1 | awk '{print $9}' | cut -f1 -d "." | cut -c 5- ) && echo $((file +1 ))` prints 1235. Something else is going on. – l0b0 Mar 04 '21 at 02:24
  • Your code breaks if the most recent file in the directory isn't of the format ABCDNNNN.XXX => so `file` is empty and `newfile=1` – DuncG Mar 04 '21 at 10:07
  • In regards to Kamil . The ls command does output the intended file. – manhasnoname Mar 04 '21 at 14:24
  • If i reproduce just this segment of code in a new script it does what I intend it to , but when added to my larger script it stops functioning. I don't get why adding it to the larger script changes what the script does though as I have specified which directory the ls command should be run on. – manhasnoname Mar 04 '21 at 14:28
  • DuncG and Kamil your comments pointed me in the right direction and it was a stupid mistake on my part. In the earlier part of my bash script I run a command that creates a file in the same directory so therefore the most recent file is no longer the file i expected. I edited my code to make that file in a new directory and now everything is working as it should. Thank you for your help everyone. – manhasnoname Mar 04 '21 at 16:23

0 Answers0