[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: command for swapping of two files or two dirs?
From: |
Greg Wooledge |
Subject: |
Re: command for swapping of two files or two dirs? |
Date: |
Fri, 26 Mar 2021 20:25:04 -0400 |
On Fri, Mar 26, 2021 at 11:28:15PM +0100, Alex fxmbsw7 Ratchev wrote:
> swap_maybe_safer() { declare t=
> while [[ -e ${t:=.$SRANDOM$SRANDOM}.} ]] && t= ; do :; done
>
> cp -p "$1" "$t"
> mv "$2" "$1"
> mv "$t" "$2"
> }
This is so sad. I can't take it any more.
# swap_files file1 file2
# Exit status:
# 0 success
# 1 user error
# 2 runtime error occurred, no side effects
# 3 runtime error occurred, with side effects
swap_files() {
if (($# != 2)); then
printf 'usage: swap_files file1 file2\nFiles must be in the same dir\n' >&2
return 1
fi
local dir dir2 temp i=0
case $1 in
*/*) dir=${1%/*} ;;
*) dir=. ;;
esac
case $2 in
*/*) dir2=${2%/*} ;;
*) dir2=. ;;
esac
if [[ $dir2 != $dir ]]; then
echo 'Files must be in the same dir' >&2
return 1
fi
while ((++i < 100)); do
temp=$dir/.$$.$RANDOM
[[ -e $temp ]] && continue
ln -- "$1" "$temp" || return 2
if ! mv -- "$2" "$1"; then
rm -- "$temp"
return 2
fi
if ! mv -- "$temp" "$2"; then
echo 'The first move succeeded, but the second failed. HELP!' >&2
return 3
fi
return 0
done
echo 'Could not find an unused temp file name' >&2
return 2
}
- Re: command for swapping of two files or two dirs?, (continued)
- Re: command for swapping of two files or two dirs?, Alex fxmbsw7 Ratchev, 2021/03/26
- Re: command for swapping of two files or two dirs?, Peng Yu, 2021/03/26
- Re: command for swapping of two files or two dirs?, Alex fxmbsw7 Ratchev, 2021/03/26
- Re: command for swapping of two files or two dirs?, Eli Schwartz, 2021/03/26
- Re: command for swapping of two files or two dirs?, Alex fxmbsw7 Ratchev, 2021/03/26
- Re: command for swapping of two files or two dirs?, Reuti, 2021/03/26
- Re: command for swapping of two files or two dirs?, Alex fxmbsw7 Ratchev, 2021/03/26
- Re: command for swapping of two files or two dirs?, Peng Yu, 2021/03/26
- Re: command for swapping of two files or two dirs?, Reuti, 2021/03/26
Re: command for swapping of two files or two dirs?, Alex fxmbsw7 Ratchev, 2021/03/26
- Re: command for swapping of two files or two dirs?,
Greg Wooledge <=