3

I have a folder structure that looks like this

/some/folder/1
/some/folder/2
...

and a symlink current that links to one of the folders. Is it possible and when how to read the target of the link, increment the name of the last folder and create a folder with that number, e.g. read the link that points to /some/folder/2 so I know the last number is 2 and increment this number to create a new folder /some/folder/3 to store new files?

I already have a script that reads the target of the link, but I have no clue how to get the last part of the path (the number) and increment it by one.

4

use readlink to get the target of a symlink:

target=$(readlink $1)

then use the power of shell, to remove everything before the last /;

id=${target##*/}

or remove everything after the last /:

base=${target%/*}

then use the power of shell to do simple arithmetic

newid=$((id+1))

finally glue them together:

newtarget=${base}/${newid}

or, in one line:

newtarget=${target%/*}/$((${target##*/}+1))
  • 1
    It's good practice to reserve all-uppercase variables to environment variables. – Stéphane Chazelas Aug 21 '14 at 14:47
  • That won't work if the link is like current -> 2 (as would be the most sensible thing to do). Use base=${target%"$id"} and newtarget=$base$newid instead. – Stéphane Chazelas Aug 21 '14 at 14:49
  • but the latter case is trivial anyhow: newtarget=$(($(readlink current) + 1 )) – umläute Aug 21 '14 at 15:35
  • 1
    Using dirname and basename would also make it more robust (also for cases where the link is like current -> 2/) – Stéphane Chazelas Aug 21 '14 at 15:43

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.