Pseudocode where incomplete pseudo try-catch after cas' comment

#!/usr/bin/env bash
# http://askubuntu.com/q/799834/25388    
# Use: `sh myScript`; sudo does not work with Matlab. 

#set -e # no rudimentary error checking
# https://stackoverflow.com/a/69808/54964


sudo dd if="/dev/zero" of="${SWAP_FILE}" bs="1M" count="${SIZE_MB}" status="progress"
sudo mkswap "${SWAP_FILE}"
sudo chmod 0600 "${SWAP_FILE}"
sudo chown root:root "${SWAP_FILE}" # http://unix.stackexchange.com/a/297153/16920

# TODO error-handling if any error, do swap
# Error-trapping here as here https://stackoverflow.com/a/185900/54964 ?   
# My proposal where I am not sure about how to connect the commands inside the first block in braces
# https://stackoverflow.com/a/22010339/54964
        sudo swapon -v "${SWAP_FILE}"
        echo "Swap enabled. Press enter to continue"; read
} || {
        echo "I will remove the swap. Press enter to continue"; read
        sudo swapoff -v "${SWAP_FILE}"
        rm -vf "${SWAP_FILE}"
        exit 1

echo "I will remove the swap. Press enter to continue"; read
sudo swapoff -v "${SWAP_FILE}"
rm -vf "${SWAP_FILE}"


dd: failed to open '/media/masi/SamiSwapVirtual/.swap_file_20.7.2016': Permission denied
mkswap: cannot open /media/masi/SamiSwapVirtual/.swap_file_20.7.2016: Permission denied
chmod: changing permissions of '/media/masi/SamiSwapVirtual/.swap_file_20.7.2016': Operation not permitted
[sudo] password for masi: 


  • dd and mkswap gives Permission denied sometimes depending on the disk so sudo there.
  • How can you put it ask your password first before running any commands in the first block of braces?

System: Linux Ubuntu 16.04 64 bit Linux kernel: 4.6
Hardware: Macbook Air 2013-mid
Related thread: Error handling in BASH

  • 1
    1. quote your variables when you use them, not just when you define them. 2. pretty much all of this has to be done as root, so just write the script without any sudo commands in it and run it as sudo myswapscript. 3. just add more swap space to the system in /etc/fstab and be done with it - do you really need to add more swap every time you run matlab? 4. even better than swap, add more RAM to the system. or RAM and swap. 5. the linux kernel's zram (compressed ram block device) makes a nice swap device, and much faster than any hdd or ssd. – cas Jul 21 '16 at 7:18
  • @cas 1) fixed. 2) does not work because Matlab does not work with sudo. – Léo Léopold Hertz 준영 Jul 21 '16 at 14:20
  • 1
    So don't run matlab with sudo. Running matlab is, or should be, entirely separate from managing swap space - which is the theme of my points 3, 4, and 5. The script that runs matlab should not be the same script that manages your swap space. If you really must do it in this crazy way, then your script that runs matlab should use sudo to run the script that adds swap space - they should be separate scripts, because they do completely different and unrelated tasks. – cas Jul 21 '16 at 14:37
  1. Running matlab is, or should be, entirely separate from managing swap space. You should separate the swap-creation/deletion parts into a separate script and then run that script with sudo - either from the command line or from your main matlab-running script.

    You should also quote your variables when you use them, not just when you define them. BTW, since your variables are fixed strings without any variable etc interpolation, you should use single-quotes when defining them. The same is true for your dd command - only the of= and count= arguments need double-quoting. The others don't need quoting at all, but single-quotes are more appropriate if you choose to quote them.

    Use double quotes when you want to embed other variables or command substitution in a variable or argument, single-quotes for fixed strings. BTW for dates, YMD sorts properly. DMY doesn't.


    SWAPFILE="/$swappath/.swap_file_$(date +%Y%m%d)" SWAP_FILE='/media/masi/SamiSwapVirtual/.swap_file_20.7.2016'

  2. You shouldn't need to add swap space just because you're running matlab. Or any other program. If you need or might need more swap space then just add it to the system once, e.g. in /etc/fstab and forget about it.

    If you can resize your partitions so that the swap partition is slightly larger than you think you'll need then do so. If not, then add a swap file in /etc/fstab.

    If swapping to an SSD, you should use the discard option so that the blocks are trimmed on every reboot. e.g.

    /dev/sda4 none swap defaults,discard 0 0

    The discard option definitely works on partitions. I'm not sure if it works on swap files too (I think it does but haven't seen any documentation that says so)

  3. Even better than adding swap space is to install more RAM in the system if the hardware allows it. You mentioned in another post that you're using a Macbook Air, which has soldered-on RAM so doesn't allow RAM upgrades.

    For other machines, this is the best option. DDR3-based systems with 4 DIMM sockets can easily and fairly cheaply be upgraded to 32GB (4x8GB DIMMs at around $50 each). DDR4-based systems with 4 DIMM sockets can easily be upgraded to 64GB (4x16GB DIMMs at around $100 each).

    (prices are approximate, in AUD, for products available in .au, and current at time of writing)

    It's possible, but harder to find and more expensive, to install 16GB DDR3 DIMMs....the price difference is large enough that it's probably worthwhile to just upgrade the motherboard and CPU to get DDR4.

  4. zram can use some of your RAM as a compressed RAM block device. For example, for a zram swap device that uses up to 4GB of RAM:

    modprobe zram num_devices=1
    echo $((4 * 1024 * 1024 * 1024)) > /sys/block/zram0/disksize
    mkswap /dev/zram0
    swapon -p 100 /dev/zram0

    You can use this if you also have a swap partition or swap file, but it makes more sense to use zswap because there is no "intelligence" about what gets kept in ZRAM swap and what gets swapped to disk. When ZRAM swap is filled, all subsequent swapped data goes to disk until there's free space in the ZRAM again.

  5. If you have a swap partition already, you can use zswap to add a dynamically resizing RAM cache with compression to your existing swap space. You can tell it which compression algorithm to use, and the maximum percentage of RAM that it's allowed to use. For example:

    echo 1 > /sys/module/zswap/parameters/enabled
    echo lz4 > /sys/module/zswap/parameters/compressor
    echo 50 > /sys/module/zswap/parameters/max_pool_percent

    This will compress any data that is swapped out, and when it gets near the maximum RAM size, it starts using the swap partition on a Least-Recently-Used (LRU) basis, so the most recently used data is more likely to stay in RAM.

    Both zram and zswap have been in the mainline kernel for several years now.

    zram or zswap can be particularly useful if you also upgrade your RAM. e.g. I recently upgraded my main system to 32GB of DDR3 and also use an SSD swap partition with zswap configured to allow up to 25% of RAM to be used for swap.

  • Can you explain more about this statement? The discard option definitely works on partitions. I'm not sure if it works on swap files too (I think it does but haven't seen any documentation that says so). What do you mean that you suspect that it does not work with swap files? Can you give an example, please. – Léo Léopold Hertz 준영 Jul 27 '16 at 13:26
  • Please, see tldp.org/HOWTO/Partition/requirements.html and 4.4.3. Where should I put my swap space? What do you think? What does it mean to Put each swap partition on the outer tracks? – Léo Léopold Hertz 준영 Jul 27 '16 at 13:30
  • 1
    I didn't say that I suspect it doesn't. I said I think it does but I haven't seen any documentation that says so. If i had an example to give, that would mean that I knew for sure whether it worked or not and I would have said so. As it was, i gave up googling after about a minute because i didn't feel it was important enough to spend more time on. If it's important to you, it's easy enough to test - just create a swap file and try to use swapon --discard=once /path/to/swapfile. – cas Jul 27 '16 at 13:33
  • the page you linked to explains what "Put each swap partition on the outer tracks" means and why they suggest it. – cas Jul 27 '16 at 13:37
  • 1
    right, with an SSD it's irrelevant. – cas Jul 27 '16 at 13:40

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.