Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[cppcheck] Reduce scope for variable.
[simgrid.git] / src / smpi / smpitools.sh
1 #!/usr/bin/env sh
2
3 # Copyright (c) 2013-2019. The SimGrid Team.
4 # All rights reserved.
5
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the license (GNU LGPL) which comes with this package.
8
9 SAVEIFS="$IFS"
10 LISTSEP="$(printf '\b')"
11
12 # Create a temporary file, with its name of the form $1_XXX$2, where XXX is replaced by an unique string.
13 # $1: prefix, $2: suffix
14 mymktemp () {
15     local_tmp=$(mktemp --suffix="$2" "$1_XXXXXXXXXX" 2> /dev/null)
16     if [ -z "$local_tmp" ]; then
17         # mktemp failed (unsupported --suffix ?), try unsafe mode
18         local_tmp=$(mktemp -u "$1_XXXXXXXXXX" 2> /dev/null)
19         if [ -z "$local_tmp" ]; then
20             # mktemp failed again (doesn't exist ?), try very unsafe mode
21             if [ -z "${mymktemp_seq}" ]; then
22                 mymktemp_seq=$(date +%d%H%M%S)
23             fi
24             local_tmp="$1_$$x${mymktemp_seq}"
25             mymktemp_seq=$((mymktemp_seq + 1))
26         fi
27         local_tmp="${local_tmp}$2"
28         # create temp file, and exit if it existed before
29         sh -C -c "true > \"${local_tmp}\"" || exit 1
30     fi
31     echo "${local_tmp}"
32 }
33
34 # Add a word to the end of a list (words separated by LISTSEP)
35 # $1: list, $2...: words to add
36 list_add () {
37     local_list="$1"
38     shift
39     if [ $# -gt 0 ]; then
40         eval local_content=\"\${$local_list}\"
41         IFS="$LISTSEP"
42         local_newcontent="$*"
43         IFS="$SAVEIFS"
44         if [ -z "$local_content" ]; then
45             local_content="$local_newcontent"
46         else
47             local_content="$local_content${LISTSEP}$local_newcontent"
48         fi
49         eval $local_list=\"\${local_content}\"
50     fi
51 }
52
53 # Like list_add, but only if first word to add ($2) is not empty
54 list_add_not_empty () {
55     if [ -n "$2" ]; then
56         list_add "$@"
57     fi
58 }
59
60 # Set contents of a list (words separated by LISTSEP)
61 # $1: list, $2...: words to set
62 list_set () {
63     eval $1=""
64     list_add "$@"
65 }
66
67 # Get the content of a list: positional parameters ($1, $2, ...) are set to the content of the list
68 # $1: list
69 # usage:  eval $(list_get list)
70 list_get () {
71     printf 'IFS="'\$'LISTSEP"; eval set -- \$%s; IFS="'\$'SAVEIFS"\n' "$1"
72 }