From 7a0dac10bf10dbf5162f15de84661af60d8550f8 Mon Sep 17 00:00:00 2001 From: Albert Ou Date: Fri, 20 Feb 2015 23:00:00 -0800 Subject: [PATCH] scripts: Enhance portability of cp_s Eliminate bashisms; target the Bourne shell and a safer subset of POSIX utilities. Furthermore, properly handle pathnames with whitespace. --- scripts/cp_s | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/scripts/cp_s b/scripts/cp_s index babc5e5d..515905c5 100755 --- a/scripts/cp_s +++ b/scripts/cp_s @@ -1,19 +1,26 @@ -#!/bin/bash -# This script emulates the cp -s command, which Mac OS doesn't support. +#!/bin/sh +# Emulate cp -s for systems without coreutils -set -e +if test -z "$1" || test -z "$2" ; then + echo "usage: ${0} srcdir destdir" >&2 + exit 1 +fi -pushd $1 > /dev/null -SRCDIR=`pwd` -DIRS=`find . -type d` -FILES=`find . -type f` -popd > /dev/null +# Portability notes: +# - Avoid set -e given its ambiguous interaction with subshells. +# - Not all shells update $PWD as required by POSIX. +# Use the pwd builtin instead. +# - Command substitution strips all trailing newlines. +# Preserve trailing newlines by appending a safety character and then +# removing it with parameter substitution, along with the newline +# appended by pwd itself. -pushd $2 > /dev/null -for i in $DIRS; do - mkdir -p $i -done -for i in $FILES; do - ln -f -s $SRCDIR/$i $i -done -popd > /dev/null +mkdir -p "$2" && +destdir=`cd "$2" && pwd && echo x` && +destdir=${destdir%??} && + +cd "$1" && +srcdir=`pwd && echo x` && +srcdir=${srcdir%??} && +find . -type d -exec mkdir -p "${destdir}/{}" \; && +find . -type f -exec ln -sf "${srcdir}/{}" "${destdir}/{}" \;