当前位置 : 主页 > 网络编程 > JavaScript >

批量创建软链接

来源:互联网 收集:自由互联 发布时间:2021-06-28
make-link.js const typeA = { label: '类型A', destPath: '/home/a/src', src: [ '/home/a/1', '/home/a/2', ]};const typeB = { label: '类型B', destPath: '/home/b/src', src: [ '/home/b/1', ]};'use strict';const fs = require('fs');const path =
make-link.js
const typeA = {
    label: '类型A',
    destPath: '/home/a/src',
    src: [
        '/home/a/1',
        '/home/a/2',
    ]
};
const typeB = {
    label: '类型B',
    destPath: '/home/b/src',
    src: [
        '/home/b/1',
    ]
};

'use strict';

const fs = require('fs');
const path = require('path');

function makeLinks(type) {
    const success = [];
    const failed = [];
    const abnormal = [];
    type.src.forEach(function (target) {
        const linkPath = path.join(type.destPath, path.basename(target));
        if (!fs.existsSync(linkPath) || !fs.readlinkSync(linkPath)) {
            try {
                fs.symlinkSync(target, linkPath, 'dir');
                success.push({ target, linkPath });
            } catch (error) {
                abnormal.push({ target, linkPath });
            }
        } else {
            failed.push({ target, linkPath });
        }
    });
    const str = `${new Array(8).fill('=').join('')} ${new Date().toLocaleString()}, ${type.label}, 成功:${success.length},失败:${failed.length},异常:${abnormal.length} ${new Array(8).fill('=').join('')}`;
    const d = new Date();
    const dirName = path.join(__dirname, 'logs');
    if (!fs.existsSync(dirName)) fs.mkdirSync(dirName);
    const fileName = path.join(dirName, `log-${d.getFullYear()}${d.getMonth()+1}${d.getDate()}.json`);
    console.log(str);

    const fileInfo = { 统计: str, 成功: success, 失败: failed, 异常: abnormal };
    fs.appendFileSync(fileName, `${JSON.stringify(fileInfo, null, '  ')}\n`);
};

makeLinks(typeA);
makeLinks(typeB);
make-link.sh
#!/bin/bash

base_src_path='' #/home/src/
base_des_path=/home/data/test/

links=(
  ########################################  A 类型  ########################################
  a/src/    /home/a/1
  a/src/    /home/a/2

  ########################################  B 类型  ########################################
  b/src/    /home/b/1
)

n=`expr ${#links[*]} - 1`
for i in `seq 0 ${n}`
do
  if [ $(($i%2)) == 0 ]
  then
    src=${base_src_path}${links[${i} + 1]}
    des=${base_des_path}${links[${i}]}
    ln -s ${src} ${des}
  fi
done

echo  ' __^__                 __^__'
echo  '( ___ )---------------( ___ )'
echo  ' | / |                 | \ |'
echo  ' | / |    ln done!     | \ |'
echo  ' | / |                 | \ |'
echo  ' |___|                 |___|'
echo  '(_____)---------------(_____)'
网友评论